babylon.max.js 3.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673
  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(1, 1)
  845. */
  846. Vector2.One = function () {
  847. return new Vector2(1, 1);
  848. };
  849. /**
  850. * Returns a new Vector2 set from the passed index element of the passed array.
  851. */
  852. Vector2.FromArray = function (array, offset) {
  853. if (offset === void 0) { offset = 0; }
  854. return new Vector2(array[offset], array[offset + 1]);
  855. };
  856. /**
  857. * Sets "result" from the passed index element of the passed array.
  858. */
  859. Vector2.FromArrayToRef = function (array, offset, result) {
  860. result.x = array[offset];
  861. result.y = array[offset + 1];
  862. };
  863. /**
  864. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  865. */
  866. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  867. var squared = amount * amount;
  868. var cubed = amount * squared;
  869. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  870. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  871. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  872. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  873. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  874. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  875. return new Vector2(x, y);
  876. };
  877. /**
  878. * 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".
  879. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  880. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  881. */
  882. Vector2.Clamp = function (value, min, max) {
  883. var x = value.x;
  884. x = (x > max.x) ? max.x : x;
  885. x = (x < min.x) ? min.x : x;
  886. var y = value.y;
  887. y = (y > max.y) ? max.y : y;
  888. y = (y < min.y) ? min.y : y;
  889. return new Vector2(x, y);
  890. };
  891. /**
  892. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  893. */
  894. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  895. var squared = amount * amount;
  896. var cubed = amount * squared;
  897. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  898. var part2 = (-2.0 * cubed) + (3.0 * squared);
  899. var part3 = (cubed - (2.0 * squared)) + amount;
  900. var part4 = cubed - squared;
  901. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  902. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  903. return new Vector2(x, y);
  904. };
  905. /**
  906. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  907. */
  908. Vector2.Lerp = function (start, end, amount) {
  909. var x = start.x + ((end.x - start.x) * amount);
  910. var y = start.y + ((end.y - start.y) * amount);
  911. return new Vector2(x, y);
  912. };
  913. /**
  914. * Returns the dot product (float) of the vector "left" and the vector "right".
  915. */
  916. Vector2.Dot = function (left, right) {
  917. return left.x * right.x + left.y * right.y;
  918. };
  919. /**
  920. * Returns a new Vector2 equal to the normalized passed vector.
  921. */
  922. Vector2.Normalize = function (vector) {
  923. var newVector = vector.clone();
  924. newVector.normalize();
  925. return newVector;
  926. };
  927. /**
  928. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  929. */
  930. Vector2.Minimize = function (left, right) {
  931. var x = (left.x < right.x) ? left.x : right.x;
  932. var y = (left.y < right.y) ? left.y : right.y;
  933. return new Vector2(x, y);
  934. };
  935. /**
  936. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  937. */
  938. Vector2.Maximize = function (left, right) {
  939. var x = (left.x > right.x) ? left.x : right.x;
  940. var y = (left.y > right.y) ? left.y : right.y;
  941. return new Vector2(x, y);
  942. };
  943. /**
  944. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  945. */
  946. Vector2.Transform = function (vector, transformation) {
  947. var r = Vector2.Zero();
  948. Vector2.TransformToRef(vector, transformation, r);
  949. return r;
  950. };
  951. /**
  952. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  953. */
  954. Vector2.TransformToRef = function (vector, transformation, result) {
  955. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  956. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  957. result.x = x;
  958. result.y = y;
  959. };
  960. /**
  961. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  962. */
  963. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  964. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  965. var sign = a < 0 ? -1 : 1;
  966. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  967. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  968. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  969. };
  970. /**
  971. * Returns the distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.Distance = function (value1, value2) {
  974. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  975. };
  976. /**
  977. * Returns the squared distance (float) between the vectors "value1" and "value2".
  978. */
  979. Vector2.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. return (x * x) + (y * y);
  983. };
  984. /**
  985. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  986. */
  987. Vector2.Center = function (value1, value2) {
  988. var center = value1.add(value2);
  989. center.scaleInPlace(0.5);
  990. return center;
  991. };
  992. /**
  993. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  994. */
  995. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  996. var l2 = Vector2.DistanceSquared(segA, segB);
  997. if (l2 === 0.0) {
  998. return Vector2.Distance(p, segA);
  999. }
  1000. var v = segB.subtract(segA);
  1001. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1002. var proj = segA.add(v.multiplyByFloats(t, t));
  1003. return Vector2.Distance(p, proj);
  1004. };
  1005. return Vector2;
  1006. }());
  1007. BABYLON.Vector2 = Vector2;
  1008. var Vector3 = (function () {
  1009. /**
  1010. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1011. * A Vector3 is the main object used in 3D geometry.
  1012. * It can represent etiher the coordinates of a point the space, either a direction.
  1013. */
  1014. function Vector3(x, y, z) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. }
  1019. /**
  1020. * Returns a string with the Vector3 coordinates.
  1021. */
  1022. Vector3.prototype.toString = function () {
  1023. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1024. };
  1025. /**
  1026. * Returns the string "Vector3"
  1027. */
  1028. Vector3.prototype.getClassName = function () {
  1029. return "Vector3";
  1030. };
  1031. /**
  1032. * Returns the Vector hash code.
  1033. */
  1034. Vector3.prototype.getHashCode = function () {
  1035. var hash = this.x || 0;
  1036. hash = (hash * 397) ^ (this.y || 0);
  1037. hash = (hash * 397) ^ (this.z || 0);
  1038. return hash;
  1039. };
  1040. // Operators
  1041. /**
  1042. * Returns a new array with three elements : the coordinates the Vector3.
  1043. */
  1044. Vector3.prototype.asArray = function () {
  1045. var result = [];
  1046. this.toArray(result, 0);
  1047. return result;
  1048. };
  1049. /**
  1050. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1051. * Returns the Vector3.
  1052. */
  1053. Vector3.prototype.toArray = function (array, index) {
  1054. if (index === void 0) { index = 0; }
  1055. array[index] = this.x;
  1056. array[index + 1] = this.y;
  1057. array[index + 2] = this.z;
  1058. return this;
  1059. };
  1060. /**
  1061. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1062. */
  1063. Vector3.prototype.toQuaternion = function () {
  1064. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1065. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1066. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1067. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1068. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1069. var cosy = Math.cos(this.y * 0.5);
  1070. var siny = Math.sin(this.y * 0.5);
  1071. result.x = coszMinusx * siny;
  1072. result.y = -sinzMinusx * siny;
  1073. result.z = sinxPlusz * cosy;
  1074. result.w = cosxPlusz * cosy;
  1075. return result;
  1076. };
  1077. /**
  1078. * Adds the passed vector to the current Vector3.
  1079. * Returns the updated Vector3.
  1080. */
  1081. Vector3.prototype.addInPlace = function (otherVector) {
  1082. this.x += otherVector.x;
  1083. this.y += otherVector.y;
  1084. this.z += otherVector.z;
  1085. return this;
  1086. };
  1087. /**
  1088. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1089. */
  1090. Vector3.prototype.add = function (otherVector) {
  1091. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1092. };
  1093. /**
  1094. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1095. * Returns the current Vector3.
  1096. */
  1097. Vector3.prototype.addToRef = function (otherVector, result) {
  1098. result.x = this.x + otherVector.x;
  1099. result.y = this.y + otherVector.y;
  1100. result.z = this.z + otherVector.z;
  1101. return this;
  1102. };
  1103. /**
  1104. * Subtract the passed vector from the current Vector3.
  1105. * Returns the updated Vector3.
  1106. */
  1107. Vector3.prototype.subtractInPlace = function (otherVector) {
  1108. this.x -= otherVector.x;
  1109. this.y -= otherVector.y;
  1110. this.z -= otherVector.z;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1115. */
  1116. Vector3.prototype.subtract = function (otherVector) {
  1117. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1118. };
  1119. /**
  1120. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1121. * Returns the current Vector3.
  1122. */
  1123. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1124. result.x = this.x - otherVector.x;
  1125. result.y = this.y - otherVector.y;
  1126. result.z = this.z - otherVector.z;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1131. */
  1132. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1133. return new Vector3(this.x - x, this.y - y, this.z - z);
  1134. };
  1135. /**
  1136. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1137. * Returns the current Vector3.
  1138. */
  1139. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1140. result.x = this.x - x;
  1141. result.y = this.y - y;
  1142. result.z = this.z - z;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1147. */
  1148. Vector3.prototype.negate = function () {
  1149. return new Vector3(-this.x, -this.y, -this.z);
  1150. };
  1151. /**
  1152. * Multiplies the Vector3 coordinates by the float "scale".
  1153. * Returns the updated Vector3.
  1154. */
  1155. Vector3.prototype.scaleInPlace = function (scale) {
  1156. this.x *= scale;
  1157. this.y *= scale;
  1158. this.z *= scale;
  1159. return this;
  1160. };
  1161. /**
  1162. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1163. */
  1164. Vector3.prototype.scale = function (scale) {
  1165. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1166. };
  1167. /**
  1168. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1169. * Returns the current Vector3.
  1170. */
  1171. Vector3.prototype.scaleToRef = function (scale, result) {
  1172. result.x = this.x * scale;
  1173. result.y = this.y * scale;
  1174. result.z = this.z * scale;
  1175. return this;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1179. */
  1180. Vector3.prototype.equals = function (otherVector) {
  1181. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1182. };
  1183. /**
  1184. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1185. */
  1186. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1187. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1188. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1189. };
  1190. /**
  1191. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1192. */
  1193. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1194. return this.x === x && this.y === y && this.z === z;
  1195. };
  1196. /**
  1197. * Muliplies the current Vector3 coordinates by the passed ones.
  1198. * Returns the updated Vector3.
  1199. */
  1200. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1201. this.x *= otherVector.x;
  1202. this.y *= otherVector.y;
  1203. this.z *= otherVector.z;
  1204. return this;
  1205. };
  1206. /**
  1207. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1208. */
  1209. Vector3.prototype.multiply = function (otherVector) {
  1210. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1211. };
  1212. /**
  1213. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1214. * Returns the current Vector3.
  1215. */
  1216. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1217. result.x = this.x * otherVector.x;
  1218. result.y = this.y * otherVector.y;
  1219. result.z = this.z * otherVector.z;
  1220. return this;
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1224. */
  1225. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1226. return new Vector3(this.x * x, this.y * y, this.z * z);
  1227. };
  1228. /**
  1229. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1230. */
  1231. Vector3.prototype.divide = function (otherVector) {
  1232. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1233. };
  1234. /**
  1235. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1236. * Returns the current Vector3.
  1237. */
  1238. Vector3.prototype.divideToRef = function (otherVector, result) {
  1239. result.x = this.x / otherVector.x;
  1240. result.y = this.y / otherVector.y;
  1241. result.z = this.z / otherVector.z;
  1242. return this;
  1243. };
  1244. /**
  1245. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1246. * Returns the updated Vector3.
  1247. */
  1248. Vector3.prototype.MinimizeInPlace = function (other) {
  1249. if (other.x < this.x)
  1250. this.x = other.x;
  1251. if (other.y < this.y)
  1252. this.y = other.y;
  1253. if (other.z < this.z)
  1254. this.z = other.z;
  1255. return this;
  1256. };
  1257. /**
  1258. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1259. * Returns the updated Vector3.
  1260. */
  1261. Vector3.prototype.MaximizeInPlace = function (other) {
  1262. if (other.x > this.x)
  1263. this.x = other.x;
  1264. if (other.y > this.y)
  1265. this.y = other.y;
  1266. if (other.z > this.z)
  1267. this.z = other.z;
  1268. return this;
  1269. };
  1270. // Properties
  1271. /**
  1272. * Returns the length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.length = function () {
  1275. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. /**
  1278. * Returns the squared length of the Vector3 (float).
  1279. */
  1280. Vector3.prototype.lengthSquared = function () {
  1281. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1282. };
  1283. // Methods
  1284. /**
  1285. * Normalize the current Vector3.
  1286. * Returns the updated Vector3.
  1287. */
  1288. Vector3.prototype.normalize = function () {
  1289. var len = this.length();
  1290. if (len === 0 || len === 1.0)
  1291. return this;
  1292. var num = 1.0 / len;
  1293. this.x *= num;
  1294. this.y *= num;
  1295. this.z *= num;
  1296. return this;
  1297. };
  1298. /**
  1299. * Returns a new Vector3 copied from the current Vector3.
  1300. */
  1301. Vector3.prototype.clone = function () {
  1302. return new Vector3(this.x, this.y, this.z);
  1303. };
  1304. /**
  1305. * Copies the passed vector coordinates to the current Vector3 ones.
  1306. * Returns the updated Vector3.
  1307. */
  1308. Vector3.prototype.copyFrom = function (source) {
  1309. this.x = source.x;
  1310. this.y = source.y;
  1311. this.z = source.z;
  1312. return this;
  1313. };
  1314. /**
  1315. * Copies the passed floats to the current Vector3 coordinates.
  1316. * Returns the updated Vector3.
  1317. */
  1318. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. return this;
  1323. };
  1324. /**
  1325. * Copies the passed floats to the current Vector3 coordinates.
  1326. * Returns the updated Vector3.
  1327. */
  1328. Vector3.prototype.set = function (x, y, z) {
  1329. return this.copyFromFloats(x, y, z);
  1330. };
  1331. // Statics
  1332. /**
  1333. *
  1334. */
  1335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1336. var d0 = Vector3.Dot(vector0, axis) - size;
  1337. var d1 = Vector3.Dot(vector1, axis) - size;
  1338. var s = d0 / (d0 - d1);
  1339. return s;
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set from the index "offset" of the passed array.
  1343. */
  1344. Vector3.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1352. * This function is deprecated. Use FromArray instead.
  1353. */
  1354. Vector3.FromFloatArray = function (array, offset) {
  1355. return Vector3.FromArray(array, offset);
  1356. };
  1357. /**
  1358. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1359. */
  1360. Vector3.FromArrayToRef = function (array, offset, result) {
  1361. result.x = array[offset];
  1362. result.y = array[offset + 1];
  1363. result.z = array[offset + 2];
  1364. };
  1365. /**
  1366. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1367. * This function is deprecated. Use FromArrayToRef instead.
  1368. */
  1369. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1370. return Vector3.FromArrayToRef(array, offset, result);
  1371. };
  1372. /**
  1373. * Sets the passed vector "result" with the passed floats.
  1374. */
  1375. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1376. result.x = x;
  1377. result.y = y;
  1378. result.z = z;
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1382. */
  1383. Vector3.Zero = function () {
  1384. return new Vector3(0.0, 0.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1388. */
  1389. Vector3.One = function () {
  1390. return new Vector3(1.0, 1.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1394. */
  1395. Vector3.Up = function () {
  1396. return new Vector3(0.0, 1.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1400. */
  1401. Vector3.Forward = function () {
  1402. return new Vector3(0.0, 0.0, 1.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1406. */
  1407. Vector3.Right = function () {
  1408. return new Vector3(1.0, 0.0, 0.0);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1412. */
  1413. Vector3.Left = function () {
  1414. return new Vector3(-1.0, 0.0, 0.0);
  1415. };
  1416. /**
  1417. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1418. * This method computes tranformed coordinates only, not transformed direction vectors.
  1419. */
  1420. Vector3.TransformCoordinates = function (vector, transformation) {
  1421. var result = Vector3.Zero();
  1422. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1423. return result;
  1424. };
  1425. /**
  1426. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1427. * This method computes tranformed coordinates only, not transformed direction vectors.
  1428. */
  1429. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1430. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1431. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1432. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1433. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1434. result.x = x / w;
  1435. result.y = y / w;
  1436. result.z = z / w;
  1437. };
  1438. /**
  1439. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1440. * This method computes tranformed coordinates only, not transformed direction vectors.
  1441. */
  1442. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1443. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1444. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1445. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1446. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1447. result.x = rx / rw;
  1448. result.y = ry / rw;
  1449. result.z = rz / rw;
  1450. };
  1451. /**
  1452. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1453. * This methods computes transformed normalized direction vectors only.
  1454. */
  1455. Vector3.TransformNormal = function (vector, transformation) {
  1456. var result = Vector3.Zero();
  1457. Vector3.TransformNormalToRef(vector, transformation, result);
  1458. return result;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1467. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1468. result.x = x;
  1469. result.y = y;
  1470. result.z = z;
  1471. };
  1472. /**
  1473. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1474. * This methods computes transformed normalized direction vectors only.
  1475. */
  1476. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1477. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1478. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1479. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1480. };
  1481. /**
  1482. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1483. */
  1484. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1485. var squared = amount * amount;
  1486. var cubed = amount * squared;
  1487. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1488. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1489. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1490. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1491. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1492. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1493. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1494. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1495. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * 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".
  1500. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1501. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1502. */
  1503. Vector3.Clamp = function (value, min, max) {
  1504. var x = value.x;
  1505. x = (x > max.x) ? max.x : x;
  1506. x = (x < min.x) ? min.x : x;
  1507. var y = value.y;
  1508. y = (y > max.y) ? max.y : y;
  1509. y = (y < min.y) ? min.y : y;
  1510. var z = value.z;
  1511. z = (z > max.z) ? max.z : z;
  1512. z = (z < min.z) ? min.z : z;
  1513. return new Vector3(x, y, z);
  1514. };
  1515. /**
  1516. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1517. */
  1518. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1519. var squared = amount * amount;
  1520. var cubed = amount * squared;
  1521. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1522. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1523. var part3 = (cubed - (2.0 * squared)) + amount;
  1524. var part4 = cubed - squared;
  1525. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1526. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1527. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1528. return new Vector3(x, y, z);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1532. */
  1533. Vector3.Lerp = function (start, end, amount) {
  1534. var result = new Vector3(0, 0, 0);
  1535. Vector3.LerpToRef(start, end, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1540. */
  1541. Vector3.LerpToRef = function (start, end, amount, result) {
  1542. result.x = start.x + ((end.x - start.x) * amount);
  1543. result.y = start.y + ((end.y - start.y) * amount);
  1544. result.z = start.z + ((end.z - start.z) * amount);
  1545. };
  1546. /**
  1547. * Returns the dot product (float) between the vectors "left" and "right".
  1548. */
  1549. Vector3.Dot = function (left, right) {
  1550. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1551. };
  1552. /**
  1553. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1554. * The cross product is then orthogonal to both "left" and "right".
  1555. */
  1556. Vector3.Cross = function (left, right) {
  1557. var result = Vector3.Zero();
  1558. Vector3.CrossToRef(left, right, result);
  1559. return result;
  1560. };
  1561. /**
  1562. * Sets the passed vector "result" with the cross product of "left" and "right".
  1563. * The cross product is then orthogonal to both "left" and "right".
  1564. */
  1565. Vector3.CrossToRef = function (left, right, result) {
  1566. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1567. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1568. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1569. result.copyFrom(MathTmp.Vector3[0]);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 as the normalization of the passed vector.
  1573. */
  1574. Vector3.Normalize = function (vector) {
  1575. var result = Vector3.Zero();
  1576. Vector3.NormalizeToRef(vector, result);
  1577. return result;
  1578. };
  1579. /**
  1580. * Sets the passed vector "result" with the normalization of the passed first vector.
  1581. */
  1582. Vector3.NormalizeToRef = function (vector, result) {
  1583. result.copyFrom(vector);
  1584. result.normalize();
  1585. };
  1586. Vector3.Project = function (vector, world, transform, viewport) {
  1587. var cw = viewport.width;
  1588. var ch = viewport.height;
  1589. var cx = viewport.x;
  1590. var cy = viewport.y;
  1591. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1592. 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);
  1593. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1594. world.multiplyToRef(transform, matrix);
  1595. matrix.multiplyToRef(viewportMatrix, matrix);
  1596. return Vector3.TransformCoordinates(vector, matrix);
  1597. };
  1598. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1599. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1600. world.multiplyToRef(transform, matrix);
  1601. matrix.invert();
  1602. source.x = source.x / viewportWidth * 2 - 1;
  1603. source.y = -(source.y / viewportHeight * 2 - 1);
  1604. var vector = Vector3.TransformCoordinates(source, matrix);
  1605. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1606. if (MathTools.WithinEpsilon(num, 1.0)) {
  1607. vector = vector.scale(1.0 / num);
  1608. }
  1609. return vector;
  1610. };
  1611. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1612. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1613. world.multiplyToRef(view, matrix);
  1614. matrix.multiplyToRef(projection, matrix);
  1615. matrix.invert();
  1616. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1617. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1618. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1619. if (MathTools.WithinEpsilon(num, 1.0)) {
  1620. vector = vector.scale(1.0 / num);
  1621. }
  1622. return vector;
  1623. };
  1624. Vector3.Minimize = function (left, right) {
  1625. var min = left.clone();
  1626. min.MinimizeInPlace(right);
  1627. return min;
  1628. };
  1629. Vector3.Maximize = function (left, right) {
  1630. var max = left.clone();
  1631. max.MaximizeInPlace(right);
  1632. return max;
  1633. };
  1634. /**
  1635. * Returns the distance (float) between the vectors "value1" and "value2".
  1636. */
  1637. Vector3.Distance = function (value1, value2) {
  1638. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1639. };
  1640. /**
  1641. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1642. */
  1643. Vector3.DistanceSquared = function (value1, value2) {
  1644. var x = value1.x - value2.x;
  1645. var y = value1.y - value2.y;
  1646. var z = value1.z - value2.z;
  1647. return (x * x) + (y * y) + (z * z);
  1648. };
  1649. /**
  1650. * Returns a new Vector3 located at the center between "value1" and "value2".
  1651. */
  1652. Vector3.Center = function (value1, value2) {
  1653. var center = value1.add(value2);
  1654. center.scaleInPlace(0.5);
  1655. return center;
  1656. };
  1657. /**
  1658. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1659. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1660. * to something in order to rotate it from its local system to the given target system.
  1661. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1662. * Returns a new Vector3.
  1663. */
  1664. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1665. var rotation = Vector3.Zero();
  1666. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1667. return rotation;
  1668. };
  1669. /**
  1670. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1671. */
  1672. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1673. var quat = MathTmp.Quaternion[0];
  1674. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1675. quat.toEulerAnglesToRef(ref);
  1676. };
  1677. return Vector3;
  1678. }());
  1679. BABYLON.Vector3 = Vector3;
  1680. //Vector4 class created for EulerAngle class conversion to Quaternion
  1681. var Vector4 = (function () {
  1682. /**
  1683. * Creates a Vector4 object from the passed floats.
  1684. */
  1685. function Vector4(x, y, z, w) {
  1686. this.x = x;
  1687. this.y = y;
  1688. this.z = z;
  1689. this.w = w;
  1690. }
  1691. /**
  1692. * Returns the string with the Vector4 coordinates.
  1693. */
  1694. Vector4.prototype.toString = function () {
  1695. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1696. };
  1697. /**
  1698. * Returns the string "Vector4".
  1699. */
  1700. Vector4.prototype.getClassName = function () {
  1701. return "Vector4";
  1702. };
  1703. /**
  1704. * Returns the Vector4 hash code.
  1705. */
  1706. Vector4.prototype.getHashCode = function () {
  1707. var hash = this.x || 0;
  1708. hash = (hash * 397) ^ (this.y || 0);
  1709. hash = (hash * 397) ^ (this.z || 0);
  1710. hash = (hash * 397) ^ (this.w || 0);
  1711. return hash;
  1712. };
  1713. // Operators
  1714. /**
  1715. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1716. */
  1717. Vector4.prototype.asArray = function () {
  1718. var result = [];
  1719. this.toArray(result, 0);
  1720. return result;
  1721. };
  1722. /**
  1723. * Populates the passed array from the passed index with the Vector4 coordinates.
  1724. * Returns the Vector4.
  1725. */
  1726. Vector4.prototype.toArray = function (array, index) {
  1727. if (index === undefined) {
  1728. index = 0;
  1729. }
  1730. array[index] = this.x;
  1731. array[index + 1] = this.y;
  1732. array[index + 2] = this.z;
  1733. array[index + 3] = this.w;
  1734. return this;
  1735. };
  1736. /**
  1737. * Adds the passed vector to the current Vector4.
  1738. * Returns the updated Vector4.
  1739. */
  1740. Vector4.prototype.addInPlace = function (otherVector) {
  1741. this.x += otherVector.x;
  1742. this.y += otherVector.y;
  1743. this.z += otherVector.z;
  1744. this.w += otherVector.w;
  1745. return this;
  1746. };
  1747. /**
  1748. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1749. */
  1750. Vector4.prototype.add = function (otherVector) {
  1751. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1752. };
  1753. /**
  1754. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1755. * Returns the current Vector4.
  1756. */
  1757. Vector4.prototype.addToRef = function (otherVector, result) {
  1758. result.x = this.x + otherVector.x;
  1759. result.y = this.y + otherVector.y;
  1760. result.z = this.z + otherVector.z;
  1761. result.w = this.w + otherVector.w;
  1762. return this;
  1763. };
  1764. /**
  1765. * Subtract in place the passed vector from the current Vector4.
  1766. * Returns the updated Vector4.
  1767. */
  1768. Vector4.prototype.subtractInPlace = function (otherVector) {
  1769. this.x -= otherVector.x;
  1770. this.y -= otherVector.y;
  1771. this.z -= otherVector.z;
  1772. this.w -= otherVector.w;
  1773. return this;
  1774. };
  1775. /**
  1776. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1777. */
  1778. Vector4.prototype.subtract = function (otherVector) {
  1779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1780. };
  1781. /**
  1782. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1783. * Returns the current Vector4.
  1784. */
  1785. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1786. result.x = this.x - otherVector.x;
  1787. result.y = this.y - otherVector.y;
  1788. result.z = this.z - otherVector.z;
  1789. result.w = this.w - otherVector.w;
  1790. return this;
  1791. };
  1792. /**
  1793. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1794. */
  1795. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1796. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1797. };
  1798. /**
  1799. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1800. * Returns the current Vector4.
  1801. */
  1802. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1803. result.x = this.x - x;
  1804. result.y = this.y - y;
  1805. result.z = this.z - z;
  1806. result.w = this.w - w;
  1807. return this;
  1808. };
  1809. /**
  1810. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1811. */
  1812. Vector4.prototype.negate = function () {
  1813. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1814. };
  1815. /**
  1816. * Multiplies the current Vector4 coordinates by scale (float).
  1817. * Returns the updated Vector4.
  1818. */
  1819. Vector4.prototype.scaleInPlace = function (scale) {
  1820. this.x *= scale;
  1821. this.y *= scale;
  1822. this.z *= scale;
  1823. this.w *= scale;
  1824. return this;
  1825. };
  1826. /**
  1827. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1828. */
  1829. Vector4.prototype.scale = function (scale) {
  1830. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1831. };
  1832. /**
  1833. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1834. * Returns the current Vector4.
  1835. */
  1836. Vector4.prototype.scaleToRef = function (scale, result) {
  1837. result.x = this.x * scale;
  1838. result.y = this.y * scale;
  1839. result.z = this.z * scale;
  1840. result.w = this.w * scale;
  1841. return this;
  1842. };
  1843. /**
  1844. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1845. */
  1846. Vector4.prototype.equals = function (otherVector) {
  1847. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1848. };
  1849. /**
  1850. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1851. */
  1852. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1853. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1854. return otherVector
  1855. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1856. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1857. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1858. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1859. };
  1860. /**
  1861. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1864. return this.x === x && this.y === y && this.z === z && this.w === w;
  1865. };
  1866. /**
  1867. * Multiplies in place the current Vector4 by the passed one.
  1868. * Returns the updated Vector4.
  1869. */
  1870. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1871. this.x *= otherVector.x;
  1872. this.y *= otherVector.y;
  1873. this.z *= otherVector.z;
  1874. this.w *= otherVector.w;
  1875. return this;
  1876. };
  1877. /**
  1878. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1879. */
  1880. Vector4.prototype.multiply = function (otherVector) {
  1881. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1882. };
  1883. /**
  1884. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1885. * Returns the current Vector4.
  1886. */
  1887. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1888. result.x = this.x * otherVector.x;
  1889. result.y = this.y * otherVector.y;
  1890. result.z = this.z * otherVector.z;
  1891. result.w = this.w * otherVector.w;
  1892. return this;
  1893. };
  1894. /**
  1895. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1896. */
  1897. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1898. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1899. };
  1900. /**
  1901. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1902. */
  1903. Vector4.prototype.divide = function (otherVector) {
  1904. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1905. };
  1906. /**
  1907. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1908. * Returns the current Vector4.
  1909. */
  1910. Vector4.prototype.divideToRef = function (otherVector, result) {
  1911. result.x = this.x / otherVector.x;
  1912. result.y = this.y / otherVector.y;
  1913. result.z = this.z / otherVector.z;
  1914. result.w = this.w / otherVector.w;
  1915. return this;
  1916. };
  1917. /**
  1918. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1919. */
  1920. Vector4.prototype.MinimizeInPlace = function (other) {
  1921. if (other.x < this.x)
  1922. this.x = other.x;
  1923. if (other.y < this.y)
  1924. this.y = other.y;
  1925. if (other.z < this.z)
  1926. this.z = other.z;
  1927. if (other.w < this.w)
  1928. this.w = other.w;
  1929. return this;
  1930. };
  1931. /**
  1932. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1933. */
  1934. Vector4.prototype.MaximizeInPlace = function (other) {
  1935. if (other.x > this.x)
  1936. this.x = other.x;
  1937. if (other.y > this.y)
  1938. this.y = other.y;
  1939. if (other.z > this.z)
  1940. this.z = other.z;
  1941. if (other.w > this.w)
  1942. this.w = other.w;
  1943. return this;
  1944. };
  1945. // Properties
  1946. /**
  1947. * Returns the Vector4 length (float).
  1948. */
  1949. Vector4.prototype.length = function () {
  1950. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1951. };
  1952. /**
  1953. * Returns the Vector4 squared length (float).
  1954. */
  1955. Vector4.prototype.lengthSquared = function () {
  1956. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1957. };
  1958. // Methods
  1959. /**
  1960. * Normalizes in place the Vector4.
  1961. * Returns the updated Vector4.
  1962. */
  1963. Vector4.prototype.normalize = function () {
  1964. var len = this.length();
  1965. if (len === 0)
  1966. return this;
  1967. var num = 1.0 / len;
  1968. this.x *= num;
  1969. this.y *= num;
  1970. this.z *= num;
  1971. this.w *= num;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1976. */
  1977. Vector4.prototype.toVector3 = function () {
  1978. return new Vector3(this.x, this.y, this.z);
  1979. };
  1980. /**
  1981. * Returns a new Vector4 copied from the current one.
  1982. */
  1983. Vector4.prototype.clone = function () {
  1984. return new Vector4(this.x, this.y, this.z, this.w);
  1985. };
  1986. /**
  1987. * Updates the current Vector4 with the passed one coordinates.
  1988. * Returns the updated Vector4.
  1989. */
  1990. Vector4.prototype.copyFrom = function (source) {
  1991. this.x = source.x;
  1992. this.y = source.y;
  1993. this.z = source.z;
  1994. this.w = source.w;
  1995. return this;
  1996. };
  1997. /**
  1998. * Updates the current Vector4 coordinates with the passed floats.
  1999. * Returns the updated Vector4.
  2000. */
  2001. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. this.w = w;
  2006. return this;
  2007. };
  2008. /**
  2009. * Updates the current Vector4 coordinates with the passed floats.
  2010. * Returns the updated Vector4.
  2011. */
  2012. Vector4.prototype.set = function (x, y, z, w) {
  2013. return this.copyFromFloats(x, y, z, w);
  2014. };
  2015. // Statics
  2016. /**
  2017. * Returns a new Vector4 set from the starting index of the passed array.
  2018. */
  2019. Vector4.FromArray = function (array, offset) {
  2020. if (!offset) {
  2021. offset = 0;
  2022. }
  2023. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2024. };
  2025. /**
  2026. * Updates the passed vector "result" from the starting index of the passed array.
  2027. */
  2028. Vector4.FromArrayToRef = function (array, offset, result) {
  2029. result.x = array[offset];
  2030. result.y = array[offset + 1];
  2031. result.z = array[offset + 2];
  2032. result.w = array[offset + 3];
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2036. */
  2037. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2038. Vector4.FromArrayToRef(array, offset, result);
  2039. };
  2040. /**
  2041. * Updates the passed vector "result" coordinates from the passed floats.
  2042. */
  2043. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2044. result.x = x;
  2045. result.y = y;
  2046. result.z = z;
  2047. result.w = w;
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2051. */
  2052. Vector4.Zero = function () {
  2053. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2054. };
  2055. /**
  2056. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2057. */
  2058. Vector4.One = function () {
  2059. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2060. };
  2061. /**
  2062. * Returns a new normalized Vector4 from the passed one.
  2063. */
  2064. Vector4.Normalize = function (vector) {
  2065. var result = Vector4.Zero();
  2066. Vector4.NormalizeToRef(vector, result);
  2067. return result;
  2068. };
  2069. /**
  2070. * Updates the passed vector "result" from the normalization of the passed one.
  2071. */
  2072. Vector4.NormalizeToRef = function (vector, result) {
  2073. result.copyFrom(vector);
  2074. result.normalize();
  2075. };
  2076. Vector4.Minimize = function (left, right) {
  2077. var min = left.clone();
  2078. min.MinimizeInPlace(right);
  2079. return min;
  2080. };
  2081. Vector4.Maximize = function (left, right) {
  2082. var max = left.clone();
  2083. max.MaximizeInPlace(right);
  2084. return max;
  2085. };
  2086. /**
  2087. * Returns the distance (float) between the vectors "value1" and "value2".
  2088. */
  2089. Vector4.Distance = function (value1, value2) {
  2090. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2091. };
  2092. /**
  2093. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2094. */
  2095. Vector4.DistanceSquared = function (value1, value2) {
  2096. var x = value1.x - value2.x;
  2097. var y = value1.y - value2.y;
  2098. var z = value1.z - value2.z;
  2099. var w = value1.w - value2.w;
  2100. return (x * x) + (y * y) + (z * z) + (w * w);
  2101. };
  2102. /**
  2103. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2104. */
  2105. Vector4.Center = function (value1, value2) {
  2106. var center = value1.add(value2);
  2107. center.scaleInPlace(0.5);
  2108. return center;
  2109. };
  2110. /**
  2111. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2112. * This methods computes transformed normalized direction vectors only.
  2113. */
  2114. Vector4.TransformNormal = function (vector, transformation) {
  2115. var result = Vector4.Zero();
  2116. Vector4.TransformNormalToRef(vector, transformation, result);
  2117. return result;
  2118. };
  2119. /**
  2120. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2121. * This methods computes transformed normalized direction vectors only.
  2122. */
  2123. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2124. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2125. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2126. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2127. result.x = x;
  2128. result.y = y;
  2129. result.z = z;
  2130. result.w = vector.w;
  2131. };
  2132. /**
  2133. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2134. * This methods computes transformed normalized direction vectors only.
  2135. */
  2136. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2137. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2138. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2139. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2140. result.w = w;
  2141. };
  2142. return Vector4;
  2143. }());
  2144. BABYLON.Vector4 = Vector4;
  2145. var Size = (function () {
  2146. /**
  2147. * Creates a Size object from the passed width and height (floats).
  2148. */
  2149. function Size(width, height) {
  2150. this.width = width;
  2151. this.height = height;
  2152. }
  2153. // Returns a string with the Size width and height.
  2154. Size.prototype.toString = function () {
  2155. return "{W: " + this.width + ", H: " + this.height + "}";
  2156. };
  2157. /**
  2158. * Returns the string "Size"
  2159. */
  2160. Size.prototype.getClassName = function () {
  2161. return "Size";
  2162. };
  2163. /**
  2164. * Returns the Size hash code.
  2165. */
  2166. Size.prototype.getHashCode = function () {
  2167. var hash = this.width || 0;
  2168. hash = (hash * 397) ^ (this.height || 0);
  2169. return hash;
  2170. };
  2171. /**
  2172. * Updates the current size from the passed one.
  2173. * Returns the updated Size.
  2174. */
  2175. Size.prototype.copyFrom = function (src) {
  2176. this.width = src.width;
  2177. this.height = src.height;
  2178. };
  2179. /**
  2180. * Updates in place the current Size from the passed floats.
  2181. * Returns the updated Size.
  2182. */
  2183. Size.prototype.copyFromFloats = function (width, height) {
  2184. this.width = width;
  2185. this.height = height;
  2186. return this;
  2187. };
  2188. /**
  2189. * Updates in place the current Size from the passed floats.
  2190. * Returns the updated Size.
  2191. */
  2192. Size.prototype.set = function (width, height) {
  2193. return this.copyFromFloats(width, height);
  2194. };
  2195. /**
  2196. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2197. */
  2198. Size.prototype.multiplyByFloats = function (w, h) {
  2199. return new Size(this.width * w, this.height * h);
  2200. };
  2201. /**
  2202. * Returns a new Size copied from the passed one.
  2203. */
  2204. Size.prototype.clone = function () {
  2205. return new Size(this.width, this.height);
  2206. };
  2207. /**
  2208. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2209. */
  2210. Size.prototype.equals = function (other) {
  2211. if (!other) {
  2212. return false;
  2213. }
  2214. return (this.width === other.width) && (this.height === other.height);
  2215. };
  2216. Object.defineProperty(Size.prototype, "surface", {
  2217. /**
  2218. * Returns the surface of the Size : width * height (float).
  2219. */
  2220. get: function () {
  2221. return this.width * this.height;
  2222. },
  2223. enumerable: true,
  2224. configurable: true
  2225. });
  2226. /**
  2227. * Returns a new Size set to (0.0, 0.0)
  2228. */
  2229. Size.Zero = function () {
  2230. return new Size(0.0, 0.0);
  2231. };
  2232. /**
  2233. * Returns a new Size set as the addition result of the current Size and the passed one.
  2234. */
  2235. Size.prototype.add = function (otherSize) {
  2236. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2237. return r;
  2238. };
  2239. /**
  2240. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2241. */
  2242. Size.prototype.subtract = function (otherSize) {
  2243. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2244. return r;
  2245. };
  2246. /**
  2247. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2248. */
  2249. Size.Lerp = function (start, end, amount) {
  2250. var w = start.width + ((end.width - start.width) * amount);
  2251. var h = start.height + ((end.height - start.height) * amount);
  2252. return new Size(w, h);
  2253. };
  2254. return Size;
  2255. }());
  2256. BABYLON.Size = Size;
  2257. var Quaternion = (function () {
  2258. /**
  2259. * Creates a new Quaternion from the passed floats.
  2260. */
  2261. function Quaternion(x, y, z, w) {
  2262. if (x === void 0) { x = 0.0; }
  2263. if (y === void 0) { y = 0.0; }
  2264. if (z === void 0) { z = 0.0; }
  2265. if (w === void 0) { w = 1.0; }
  2266. this.x = x;
  2267. this.y = y;
  2268. this.z = z;
  2269. this.w = w;
  2270. }
  2271. /**
  2272. * Returns a string with the Quaternion coordinates.
  2273. */
  2274. Quaternion.prototype.toString = function () {
  2275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2276. };
  2277. /**
  2278. * Returns the string "Quaternion".
  2279. */
  2280. Quaternion.prototype.getClassName = function () {
  2281. return "Quaternion";
  2282. };
  2283. /**
  2284. * Returns the Quaternion hash code.
  2285. */
  2286. Quaternion.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. hash = (hash * 397) ^ (this.z || 0);
  2290. hash = (hash * 397) ^ (this.w || 0);
  2291. return hash;
  2292. };
  2293. /**
  2294. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2295. */
  2296. Quaternion.prototype.asArray = function () {
  2297. return [this.x, this.y, this.z, this.w];
  2298. };
  2299. /**
  2300. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2301. */
  2302. Quaternion.prototype.equals = function (otherQuaternion) {
  2303. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2304. };
  2305. /**
  2306. * Returns a new Quaternion copied from the current one.
  2307. */
  2308. Quaternion.prototype.clone = function () {
  2309. return new Quaternion(this.x, this.y, this.z, this.w);
  2310. };
  2311. /**
  2312. * Updates the current Quaternion from the passed one coordinates.
  2313. * Returns the updated Quaterion.
  2314. */
  2315. Quaternion.prototype.copyFrom = function (other) {
  2316. this.x = other.x;
  2317. this.y = other.y;
  2318. this.z = other.z;
  2319. this.w = other.w;
  2320. return this;
  2321. };
  2322. /**
  2323. * Updates the current Quaternion from the passed float coordinates.
  2324. * Returns the updated Quaterion.
  2325. */
  2326. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2327. this.x = x;
  2328. this.y = y;
  2329. this.z = z;
  2330. this.w = w;
  2331. return this;
  2332. };
  2333. /**
  2334. * Updates the current Quaternion from the passed float coordinates.
  2335. * Returns the updated Quaterion.
  2336. */
  2337. Quaternion.prototype.set = function (x, y, z, w) {
  2338. return this.copyFromFloats(x, y, z, w);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2342. */
  2343. Quaternion.prototype.add = function (other) {
  2344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2345. };
  2346. /**
  2347. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2348. */
  2349. Quaternion.prototype.subtract = function (other) {
  2350. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2351. };
  2352. /**
  2353. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2354. */
  2355. Quaternion.prototype.scale = function (value) {
  2356. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2357. };
  2358. /**
  2359. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2360. */
  2361. Quaternion.prototype.multiply = function (q1) {
  2362. var result = new Quaternion(0, 0, 0, 1.0);
  2363. this.multiplyToRef(q1, result);
  2364. return result;
  2365. };
  2366. /**
  2367. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2368. * Returns the current Quaternion.
  2369. */
  2370. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2371. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2372. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2373. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2374. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2375. result.copyFromFloats(x, y, z, w);
  2376. return this;
  2377. };
  2378. /**
  2379. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.multiplyInPlace = function (q1) {
  2383. this.multiplyToRef(q1, this);
  2384. return this;
  2385. };
  2386. /**
  2387. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2388. * Returns the current Quaternion.
  2389. */
  2390. Quaternion.prototype.conjugateToRef = function (ref) {
  2391. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2392. return this;
  2393. };
  2394. /**
  2395. * Conjugates in place the current Quaternion.
  2396. * Returns the updated Quaternion.
  2397. */
  2398. Quaternion.prototype.conjugateInPlace = function () {
  2399. this.x *= -1;
  2400. this.y *= -1;
  2401. this.z *= -1;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2406. */
  2407. Quaternion.prototype.conjugate = function () {
  2408. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2409. return result;
  2410. };
  2411. /**
  2412. * Returns the Quaternion length (float).
  2413. */
  2414. Quaternion.prototype.length = function () {
  2415. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2416. };
  2417. /**
  2418. * Normalize in place the current Quaternion.
  2419. * Returns the updated Quaternion.
  2420. */
  2421. Quaternion.prototype.normalize = function () {
  2422. var length = 1.0 / this.length();
  2423. this.x *= length;
  2424. this.y *= length;
  2425. this.z *= length;
  2426. this.w *= length;
  2427. return this;
  2428. };
  2429. /**
  2430. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2431. */
  2432. Quaternion.prototype.toEulerAngles = function (order) {
  2433. if (order === void 0) { order = "YZX"; }
  2434. var result = Vector3.Zero();
  2435. this.toEulerAnglesToRef(result, order);
  2436. return result;
  2437. };
  2438. /**
  2439. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2440. * Returns the current Quaternion.
  2441. */
  2442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2443. if (order === void 0) { order = "YZX"; }
  2444. var qz = this.z;
  2445. var qx = this.x;
  2446. var qy = this.y;
  2447. var qw = this.w;
  2448. var sqw = qw * qw;
  2449. var sqz = qz * qz;
  2450. var sqx = qx * qx;
  2451. var sqy = qy * qy;
  2452. var zAxisY = qy * qz - qx * qw;
  2453. var limit = .4999999;
  2454. if (zAxisY < -limit) {
  2455. result.y = 2 * Math.atan2(qy, qw);
  2456. result.x = Math.PI / 2;
  2457. result.z = 0;
  2458. }
  2459. else if (zAxisY > limit) {
  2460. result.y = 2 * Math.atan2(qy, qw);
  2461. result.x = -Math.PI / 2;
  2462. result.z = 0;
  2463. }
  2464. else {
  2465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2468. }
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the passed rotation matrix with the current Quaternion values.
  2473. * Returns the current Quaternion.
  2474. */
  2475. Quaternion.prototype.toRotationMatrix = function (result) {
  2476. var xx = this.x * this.x;
  2477. var yy = this.y * this.y;
  2478. var zz = this.z * this.z;
  2479. var xy = this.x * this.y;
  2480. var zw = this.z * this.w;
  2481. var zx = this.z * this.x;
  2482. var yw = this.y * this.w;
  2483. var yz = this.y * this.z;
  2484. var xw = this.x * this.w;
  2485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2486. result.m[1] = 2.0 * (xy + zw);
  2487. result.m[2] = 2.0 * (zx - yw);
  2488. result.m[3] = 0;
  2489. result.m[4] = 2.0 * (xy - zw);
  2490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2491. result.m[6] = 2.0 * (yz + xw);
  2492. result.m[7] = 0;
  2493. result.m[8] = 2.0 * (zx + yw);
  2494. result.m[9] = 2.0 * (yz - xw);
  2495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2496. result.m[11] = 0;
  2497. result.m[12] = 0;
  2498. result.m[13] = 0;
  2499. result.m[14] = 0;
  2500. result.m[15] = 1.0;
  2501. result._markAsUpdated();
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion from the passed rotation matrix values.
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2509. Quaternion.FromRotationMatrixToRef(matrix, this);
  2510. return this;
  2511. };
  2512. // Statics
  2513. /**
  2514. * Returns a new Quaternion set from the passed rotation matrix values.
  2515. */
  2516. Quaternion.FromRotationMatrix = function (matrix) {
  2517. var result = new Quaternion();
  2518. Quaternion.FromRotationMatrixToRef(matrix, result);
  2519. return result;
  2520. };
  2521. /**
  2522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2523. */
  2524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2525. var data = matrix.m;
  2526. var m11 = data[0], m12 = data[4], m13 = data[8];
  2527. var m21 = data[1], m22 = data[5], m23 = data[9];
  2528. var m31 = data[2], m32 = data[6], m33 = data[10];
  2529. var trace = m11 + m22 + m33;
  2530. var s;
  2531. if (trace > 0) {
  2532. s = 0.5 / Math.sqrt(trace + 1.0);
  2533. result.w = 0.25 / s;
  2534. result.x = (m32 - m23) * s;
  2535. result.y = (m13 - m31) * s;
  2536. result.z = (m21 - m12) * s;
  2537. }
  2538. else if (m11 > m22 && m11 > m33) {
  2539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2540. result.w = (m32 - m23) / s;
  2541. result.x = 0.25 * s;
  2542. result.y = (m12 + m21) / s;
  2543. result.z = (m13 + m31) / s;
  2544. }
  2545. else if (m22 > m33) {
  2546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2547. result.w = (m13 - m31) / s;
  2548. result.x = (m12 + m21) / s;
  2549. result.y = 0.25 * s;
  2550. result.z = (m23 + m32) / s;
  2551. }
  2552. else {
  2553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2554. result.w = (m21 - m12) / s;
  2555. result.x = (m13 + m31) / s;
  2556. result.y = (m23 + m32) / s;
  2557. result.z = 0.25 * s;
  2558. }
  2559. };
  2560. /**
  2561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2562. */
  2563. Quaternion.Zero = function () {
  2564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2565. };
  2566. /**
  2567. * Returns a new Quaternion as the inverted current Quaternion.
  2568. */
  2569. Quaternion.Inverse = function (q) {
  2570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2571. };
  2572. /**
  2573. * Returns the identity Quaternion.
  2574. */
  2575. Quaternion.Identity = function () {
  2576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2577. };
  2578. Quaternion.IsIdentity = function (quaternion) {
  2579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2580. };
  2581. /**
  2582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2583. */
  2584. Quaternion.RotationAxis = function (axis, angle) {
  2585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2586. };
  2587. /**
  2588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2589. */
  2590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2591. var sin = Math.sin(angle / 2);
  2592. axis.normalize();
  2593. result.w = Math.cos(angle / 2);
  2594. result.x = axis.x * sin;
  2595. result.y = axis.y * sin;
  2596. result.z = axis.z * sin;
  2597. return result;
  2598. };
  2599. /**
  2600. * Retuns a new Quaternion set from the starting index of the passed array.
  2601. */
  2602. Quaternion.FromArray = function (array, offset) {
  2603. if (!offset) {
  2604. offset = 0;
  2605. }
  2606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2607. };
  2608. /**
  2609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2610. */
  2611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2612. var q = new Quaternion();
  2613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2614. return q;
  2615. };
  2616. /**
  2617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2618. */
  2619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2621. var halfRoll = roll * 0.5;
  2622. var halfPitch = pitch * 0.5;
  2623. var halfYaw = yaw * 0.5;
  2624. var sinRoll = Math.sin(halfRoll);
  2625. var cosRoll = Math.cos(halfRoll);
  2626. var sinPitch = Math.sin(halfPitch);
  2627. var cosPitch = Math.cos(halfPitch);
  2628. var sinYaw = Math.sin(halfYaw);
  2629. var cosYaw = Math.cos(halfYaw);
  2630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2634. };
  2635. /**
  2636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2637. */
  2638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2639. var result = new Quaternion();
  2640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2641. return result;
  2642. };
  2643. /**
  2644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2645. */
  2646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2647. // Produces a quaternion from Euler angles in the z-x-z orientation
  2648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2650. var halfBeta = beta * 0.5;
  2651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2655. };
  2656. /**
  2657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2658. * cf to Vector3.RotationFromAxis() documentation.
  2659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2660. */
  2661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2664. return quat;
  2665. };
  2666. /**
  2667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2668. * cf to Vector3.RotationFromAxis() documentation.
  2669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2670. */
  2671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2672. var rotMat = MathTmp.Matrix[0];
  2673. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2674. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2675. };
  2676. Quaternion.Slerp = function (left, right, amount) {
  2677. var result = Quaternion.Identity();
  2678. Quaternion.SlerpToRef(left, right, amount, result);
  2679. return result;
  2680. };
  2681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2682. var num2;
  2683. var num3;
  2684. var num = amount;
  2685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2686. var flag = false;
  2687. if (num4 < 0) {
  2688. flag = true;
  2689. num4 = -num4;
  2690. }
  2691. if (num4 > 0.999999) {
  2692. num3 = 1 - num;
  2693. num2 = flag ? -num : num;
  2694. }
  2695. else {
  2696. var num5 = Math.acos(num4);
  2697. var num6 = (1.0 / Math.sin(num5));
  2698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2700. }
  2701. result.x = (num3 * left.x) + (num2 * right.x);
  2702. result.y = (num3 * left.y) + (num2 * right.y);
  2703. result.z = (num3 * left.z) + (num2 * right.z);
  2704. result.w = (num3 * left.w) + (num2 * right.w);
  2705. };
  2706. /**
  2707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2708. */
  2709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2710. var squared = amount * amount;
  2711. var cubed = amount * squared;
  2712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2714. var part3 = (cubed - (2.0 * squared)) + amount;
  2715. var part4 = cubed - squared;
  2716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2720. return new Quaternion(x, y, z, w);
  2721. };
  2722. return Quaternion;
  2723. }());
  2724. BABYLON.Quaternion = Quaternion;
  2725. var Matrix = (function () {
  2726. function Matrix() {
  2727. this.m = new Float32Array(16);
  2728. this._markAsUpdated();
  2729. }
  2730. Matrix.prototype._markAsUpdated = function () {
  2731. this.updateFlag = Matrix._updateFlagSeed++;
  2732. };
  2733. // Properties
  2734. /**
  2735. * Boolean : True is the matrix is the identity matrix
  2736. */
  2737. Matrix.prototype.isIdentity = function () {
  2738. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2739. return false;
  2740. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2741. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2742. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2743. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2744. return false;
  2745. return true;
  2746. };
  2747. /**
  2748. * Returns the matrix determinant (float).
  2749. */
  2750. Matrix.prototype.determinant = function () {
  2751. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2752. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2753. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2754. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2755. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2756. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2757. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2758. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2759. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2760. };
  2761. // Methods
  2762. /**
  2763. * Returns the matrix underlying array.
  2764. */
  2765. Matrix.prototype.toArray = function () {
  2766. return this.m;
  2767. };
  2768. /**
  2769. * Returns the matrix underlying array.
  2770. */
  2771. Matrix.prototype.asArray = function () {
  2772. return this.toArray();
  2773. };
  2774. /**
  2775. * Inverts in place the Matrix.
  2776. * Returns the Matrix inverted.
  2777. */
  2778. Matrix.prototype.invert = function () {
  2779. this.invertToRef(this);
  2780. return this;
  2781. };
  2782. /**
  2783. * Sets all the matrix elements to zero.
  2784. * Returns the Matrix.
  2785. */
  2786. Matrix.prototype.reset = function () {
  2787. for (var index = 0; index < 16; index++) {
  2788. this.m[index] = 0.0;
  2789. }
  2790. this._markAsUpdated();
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2795. */
  2796. Matrix.prototype.add = function (other) {
  2797. var result = new Matrix();
  2798. this.addToRef(other, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2803. * Returns the Matrix.
  2804. */
  2805. Matrix.prototype.addToRef = function (other, result) {
  2806. for (var index = 0; index < 16; index++) {
  2807. result.m[index] = this.m[index] + other.m[index];
  2808. }
  2809. result._markAsUpdated();
  2810. return this;
  2811. };
  2812. /**
  2813. * Adds in place the passed matrix to the current Matrix.
  2814. * Returns the updated Matrix.
  2815. */
  2816. Matrix.prototype.addToSelf = function (other) {
  2817. for (var index = 0; index < 16; index++) {
  2818. this.m[index] += other.m[index];
  2819. }
  2820. this._markAsUpdated();
  2821. return this;
  2822. };
  2823. /**
  2824. * Sets the passed matrix with the current inverted Matrix.
  2825. * Returns the unmodified current Matrix.
  2826. */
  2827. Matrix.prototype.invertToRef = function (other) {
  2828. var l1 = this.m[0];
  2829. var l2 = this.m[1];
  2830. var l3 = this.m[2];
  2831. var l4 = this.m[3];
  2832. var l5 = this.m[4];
  2833. var l6 = this.m[5];
  2834. var l7 = this.m[6];
  2835. var l8 = this.m[7];
  2836. var l9 = this.m[8];
  2837. var l10 = this.m[9];
  2838. var l11 = this.m[10];
  2839. var l12 = this.m[11];
  2840. var l13 = this.m[12];
  2841. var l14 = this.m[13];
  2842. var l15 = this.m[14];
  2843. var l16 = this.m[15];
  2844. var l17 = (l11 * l16) - (l12 * l15);
  2845. var l18 = (l10 * l16) - (l12 * l14);
  2846. var l19 = (l10 * l15) - (l11 * l14);
  2847. var l20 = (l9 * l16) - (l12 * l13);
  2848. var l21 = (l9 * l15) - (l11 * l13);
  2849. var l22 = (l9 * l14) - (l10 * l13);
  2850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2855. var l28 = (l7 * l16) - (l8 * l15);
  2856. var l29 = (l6 * l16) - (l8 * l14);
  2857. var l30 = (l6 * l15) - (l7 * l14);
  2858. var l31 = (l5 * l16) - (l8 * l13);
  2859. var l32 = (l5 * l15) - (l7 * l13);
  2860. var l33 = (l5 * l14) - (l6 * l13);
  2861. var l34 = (l7 * l12) - (l8 * l11);
  2862. var l35 = (l6 * l12) - (l8 * l10);
  2863. var l36 = (l6 * l11) - (l7 * l10);
  2864. var l37 = (l5 * l12) - (l8 * l9);
  2865. var l38 = (l5 * l11) - (l7 * l9);
  2866. var l39 = (l5 * l10) - (l6 * l9);
  2867. other.m[0] = l23 * l27;
  2868. other.m[4] = l24 * l27;
  2869. other.m[8] = l25 * l27;
  2870. other.m[12] = l26 * l27;
  2871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2883. other._markAsUpdated();
  2884. return this;
  2885. };
  2886. /**
  2887. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2888. * Returns the updated Matrix.
  2889. */
  2890. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2891. this.m[12] = x;
  2892. this.m[13] = y;
  2893. this.m[14] = z;
  2894. this._markAsUpdated();
  2895. return this;
  2896. };
  2897. /**
  2898. * Inserts the translation vector in the current Matrix.
  2899. * Returns the updated Matrix.
  2900. */
  2901. Matrix.prototype.setTranslation = function (vector3) {
  2902. this.m[12] = vector3.x;
  2903. this.m[13] = vector3.y;
  2904. this.m[14] = vector3.z;
  2905. this._markAsUpdated();
  2906. return this;
  2907. };
  2908. /**
  2909. * Returns a new Vector3 as the extracted translation from the Matrix.
  2910. */
  2911. Matrix.prototype.getTranslation = function () {
  2912. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2913. };
  2914. /**
  2915. * Fill a Vector3 with the extracted translation from the Matrix.
  2916. */
  2917. Matrix.prototype.getTranslationToRef = function (result) {
  2918. result.x = this.m[12];
  2919. result.y = this.m[13];
  2920. result.z = this.m[14];
  2921. return this;
  2922. };
  2923. /**
  2924. * Remove rotation and scaling part from the Matrix.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.removeRotationAndScaling = function () {
  2928. this.setRowFromFloats(0, 1, 0, 0, 0);
  2929. this.setRowFromFloats(1, 0, 1, 0, 0);
  2930. this.setRowFromFloats(2, 0, 0, 1, 0);
  2931. return this;
  2932. };
  2933. /**
  2934. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2935. */
  2936. Matrix.prototype.multiply = function (other) {
  2937. var result = new Matrix();
  2938. this.multiplyToRef(other, result);
  2939. return result;
  2940. };
  2941. /**
  2942. * Updates the current Matrix from the passed one values.
  2943. * Returns the updated Matrix.
  2944. */
  2945. Matrix.prototype.copyFrom = function (other) {
  2946. for (var index = 0; index < 16; index++) {
  2947. this.m[index] = other.m[index];
  2948. }
  2949. this._markAsUpdated();
  2950. return this;
  2951. };
  2952. /**
  2953. * Populates the passed array from the starting index with the Matrix values.
  2954. * Returns the Matrix.
  2955. */
  2956. Matrix.prototype.copyToArray = function (array, offset) {
  2957. if (offset === void 0) { offset = 0; }
  2958. for (var index = 0; index < 16; index++) {
  2959. array[offset + index] = this.m[index];
  2960. }
  2961. return this;
  2962. };
  2963. /**
  2964. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2965. */
  2966. Matrix.prototype.multiplyToRef = function (other, result) {
  2967. this.multiplyToArray(other, result.m, 0);
  2968. result._markAsUpdated();
  2969. return this;
  2970. };
  2971. /**
  2972. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2973. */
  2974. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2975. var tm0 = this.m[0];
  2976. var tm1 = this.m[1];
  2977. var tm2 = this.m[2];
  2978. var tm3 = this.m[3];
  2979. var tm4 = this.m[4];
  2980. var tm5 = this.m[5];
  2981. var tm6 = this.m[6];
  2982. var tm7 = this.m[7];
  2983. var tm8 = this.m[8];
  2984. var tm9 = this.m[9];
  2985. var tm10 = this.m[10];
  2986. var tm11 = this.m[11];
  2987. var tm12 = this.m[12];
  2988. var tm13 = this.m[13];
  2989. var tm14 = this.m[14];
  2990. var tm15 = this.m[15];
  2991. var om0 = other.m[0];
  2992. var om1 = other.m[1];
  2993. var om2 = other.m[2];
  2994. var om3 = other.m[3];
  2995. var om4 = other.m[4];
  2996. var om5 = other.m[5];
  2997. var om6 = other.m[6];
  2998. var om7 = other.m[7];
  2999. var om8 = other.m[8];
  3000. var om9 = other.m[9];
  3001. var om10 = other.m[10];
  3002. var om11 = other.m[11];
  3003. var om12 = other.m[12];
  3004. var om13 = other.m[13];
  3005. var om14 = other.m[14];
  3006. var om15 = other.m[15];
  3007. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3008. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3009. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3010. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3011. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3012. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3013. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3014. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3015. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3016. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3017. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3018. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3019. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3020. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3021. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3022. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3023. return this;
  3024. };
  3025. /**
  3026. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3027. */
  3028. Matrix.prototype.equals = function (value) {
  3029. return value &&
  3030. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3031. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3032. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3033. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3034. };
  3035. /**
  3036. * Returns a new Matrix from the current Matrix.
  3037. */
  3038. Matrix.prototype.clone = function () {
  3039. 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]);
  3040. };
  3041. /**
  3042. * Returns the string "Matrix"
  3043. */
  3044. Matrix.prototype.getClassName = function () {
  3045. return "Matrix";
  3046. };
  3047. /**
  3048. * Returns the Matrix hash code.
  3049. */
  3050. Matrix.prototype.getHashCode = function () {
  3051. var hash = this.m[0] || 0;
  3052. for (var i = 1; i < 16; i++) {
  3053. hash = (hash * 397) ^ (this.m[i] || 0);
  3054. }
  3055. return hash;
  3056. };
  3057. /**
  3058. * Decomposes the current Matrix into :
  3059. * - a scale vector3 passed as a reference to update,
  3060. * - a rotation quaternion passed as a reference to update,
  3061. * - a translation vector3 passed as a reference to update.
  3062. * Returns the boolean `true`.
  3063. */
  3064. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3065. translation.x = this.m[12];
  3066. translation.y = this.m[13];
  3067. translation.z = this.m[14];
  3068. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3069. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3070. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3071. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3072. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3073. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3074. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3075. rotation.x = 0;
  3076. rotation.y = 0;
  3077. rotation.z = 0;
  3078. rotation.w = 1;
  3079. return false;
  3080. }
  3081. 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]);
  3082. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3083. return true;
  3084. };
  3085. /**
  3086. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3087. */
  3088. Matrix.prototype.getRotationMatrix = function () {
  3089. var result = Matrix.Identity();
  3090. this.getRotationMatrixToRef(result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3095. * Returns the current Matrix.
  3096. */
  3097. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3098. var m = this.m;
  3099. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3100. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3101. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3102. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3103. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3104. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3105. 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);
  3106. return this;
  3107. };
  3108. // Statics
  3109. /**
  3110. * Returns a new Matrix set from the starting index of the passed array.
  3111. */
  3112. Matrix.FromArray = function (array, offset) {
  3113. var result = new Matrix();
  3114. if (!offset) {
  3115. offset = 0;
  3116. }
  3117. Matrix.FromArrayToRef(array, offset, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed "result" matrix from the starting index of the passed array.
  3122. */
  3123. Matrix.FromArrayToRef = function (array, offset, result) {
  3124. for (var index = 0; index < 16; index++) {
  3125. result.m[index] = array[index + offset];
  3126. }
  3127. result._markAsUpdated();
  3128. };
  3129. /**
  3130. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3131. */
  3132. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3133. for (var index = 0; index < 16; index++) {
  3134. result.m[index] = array[index + offset] * scale;
  3135. }
  3136. result._markAsUpdated();
  3137. };
  3138. /**
  3139. * Sets the passed matrix "result" with the 16 passed floats.
  3140. */
  3141. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3142. result.m[0] = initialM11;
  3143. result.m[1] = initialM12;
  3144. result.m[2] = initialM13;
  3145. result.m[3] = initialM14;
  3146. result.m[4] = initialM21;
  3147. result.m[5] = initialM22;
  3148. result.m[6] = initialM23;
  3149. result.m[7] = initialM24;
  3150. result.m[8] = initialM31;
  3151. result.m[9] = initialM32;
  3152. result.m[10] = initialM33;
  3153. result.m[11] = initialM34;
  3154. result.m[12] = initialM41;
  3155. result.m[13] = initialM42;
  3156. result.m[14] = initialM43;
  3157. result.m[15] = initialM44;
  3158. result._markAsUpdated();
  3159. };
  3160. /**
  3161. * Returns the index-th row of the current matrix as a new Vector4.
  3162. */
  3163. Matrix.prototype.getRow = function (index) {
  3164. if (index < 0 || index > 3) {
  3165. return null;
  3166. }
  3167. var i = index * 4;
  3168. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3169. };
  3170. /**
  3171. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3172. * Returns the updated Matrix.
  3173. */
  3174. Matrix.prototype.setRow = function (index, row) {
  3175. if (index < 0 || index > 3) {
  3176. return this;
  3177. }
  3178. var i = index * 4;
  3179. this.m[i + 0] = row.x;
  3180. this.m[i + 1] = row.y;
  3181. this.m[i + 2] = row.z;
  3182. this.m[i + 3] = row.w;
  3183. this._markAsUpdated();
  3184. return this;
  3185. };
  3186. /**
  3187. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3188. * Returns the updated Matrix.
  3189. */
  3190. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3191. if (index < 0 || index > 3) {
  3192. return this;
  3193. }
  3194. var i = index * 4;
  3195. this.m[i + 0] = x;
  3196. this.m[i + 1] = y;
  3197. this.m[i + 2] = z;
  3198. this.m[i + 3] = w;
  3199. this._markAsUpdated();
  3200. return this;
  3201. };
  3202. /**
  3203. * Returns a new Matrix set from the 16 passed floats.
  3204. */
  3205. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3206. var result = new Matrix();
  3207. result.m[0] = initialM11;
  3208. result.m[1] = initialM12;
  3209. result.m[2] = initialM13;
  3210. result.m[3] = initialM14;
  3211. result.m[4] = initialM21;
  3212. result.m[5] = initialM22;
  3213. result.m[6] = initialM23;
  3214. result.m[7] = initialM24;
  3215. result.m[8] = initialM31;
  3216. result.m[9] = initialM32;
  3217. result.m[10] = initialM33;
  3218. result.m[11] = initialM34;
  3219. result.m[12] = initialM41;
  3220. result.m[13] = initialM42;
  3221. result.m[14] = initialM43;
  3222. result.m[15] = initialM44;
  3223. return result;
  3224. };
  3225. /**
  3226. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3227. */
  3228. Matrix.Compose = function (scale, rotation, translation) {
  3229. var result = Matrix.Identity();
  3230. Matrix.ComposeToRef(scale, rotation, translation, result);
  3231. return result;
  3232. };
  3233. /**
  3234. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3235. */
  3236. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3237. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3238. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3239. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3240. result.setTranslation(translation);
  3241. };
  3242. /**
  3243. * Returns a new indentity Matrix.
  3244. */
  3245. Matrix.Identity = function () {
  3246. 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);
  3247. };
  3248. /**
  3249. * Sets the passed "result" as an identity matrix.
  3250. */
  3251. Matrix.IdentityToRef = function (result) {
  3252. 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);
  3253. };
  3254. /**
  3255. * Returns a new zero Matrix.
  3256. */
  3257. Matrix.Zero = function () {
  3258. 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);
  3259. };
  3260. /**
  3261. * Returns a new rotation matrix for "angle" radians around the X axis.
  3262. */
  3263. Matrix.RotationX = function (angle) {
  3264. var result = new Matrix();
  3265. Matrix.RotationXToRef(angle, result);
  3266. return result;
  3267. };
  3268. /**
  3269. * Returns a new Matrix as the passed inverted one.
  3270. */
  3271. Matrix.Invert = function (source) {
  3272. var result = new Matrix();
  3273. source.invertToRef(result);
  3274. return result;
  3275. };
  3276. /**
  3277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3278. */
  3279. Matrix.RotationXToRef = function (angle, result) {
  3280. var s = Math.sin(angle);
  3281. var c = Math.cos(angle);
  3282. result.m[0] = 1.0;
  3283. result.m[15] = 1.0;
  3284. result.m[5] = c;
  3285. result.m[10] = c;
  3286. result.m[9] = -s;
  3287. result.m[6] = s;
  3288. result.m[1] = 0.0;
  3289. result.m[2] = 0.0;
  3290. result.m[3] = 0.0;
  3291. result.m[4] = 0.0;
  3292. result.m[7] = 0.0;
  3293. result.m[8] = 0.0;
  3294. result.m[11] = 0.0;
  3295. result.m[12] = 0.0;
  3296. result.m[13] = 0.0;
  3297. result.m[14] = 0.0;
  3298. result._markAsUpdated();
  3299. };
  3300. /**
  3301. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3302. */
  3303. Matrix.RotationY = function (angle) {
  3304. var result = new Matrix();
  3305. Matrix.RotationYToRef(angle, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3310. */
  3311. Matrix.RotationYToRef = function (angle, result) {
  3312. var s = Math.sin(angle);
  3313. var c = Math.cos(angle);
  3314. result.m[5] = 1.0;
  3315. result.m[15] = 1.0;
  3316. result.m[0] = c;
  3317. result.m[2] = -s;
  3318. result.m[8] = s;
  3319. result.m[10] = c;
  3320. result.m[1] = 0.0;
  3321. result.m[3] = 0.0;
  3322. result.m[4] = 0.0;
  3323. result.m[6] = 0.0;
  3324. result.m[7] = 0.0;
  3325. result.m[9] = 0.0;
  3326. result.m[11] = 0.0;
  3327. result.m[12] = 0.0;
  3328. result.m[13] = 0.0;
  3329. result.m[14] = 0.0;
  3330. result._markAsUpdated();
  3331. };
  3332. /**
  3333. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3334. */
  3335. Matrix.RotationZ = function (angle) {
  3336. var result = new Matrix();
  3337. Matrix.RotationZToRef(angle, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3342. */
  3343. Matrix.RotationZToRef = function (angle, result) {
  3344. var s = Math.sin(angle);
  3345. var c = Math.cos(angle);
  3346. result.m[10] = 1.0;
  3347. result.m[15] = 1.0;
  3348. result.m[0] = c;
  3349. result.m[1] = s;
  3350. result.m[4] = -s;
  3351. result.m[5] = c;
  3352. result.m[2] = 0.0;
  3353. result.m[3] = 0.0;
  3354. result.m[6] = 0.0;
  3355. result.m[7] = 0.0;
  3356. result.m[8] = 0.0;
  3357. result.m[9] = 0.0;
  3358. result.m[11] = 0.0;
  3359. result.m[12] = 0.0;
  3360. result.m[13] = 0.0;
  3361. result.m[14] = 0.0;
  3362. result._markAsUpdated();
  3363. };
  3364. /**
  3365. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3366. */
  3367. Matrix.RotationAxis = function (axis, angle) {
  3368. var result = Matrix.Zero();
  3369. Matrix.RotationAxisToRef(axis, angle, result);
  3370. return result;
  3371. };
  3372. /**
  3373. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3374. */
  3375. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3376. var s = Math.sin(-angle);
  3377. var c = Math.cos(-angle);
  3378. var c1 = 1 - c;
  3379. axis.normalize();
  3380. result.m[0] = (axis.x * axis.x) * c1 + c;
  3381. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3382. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3383. result.m[3] = 0.0;
  3384. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3385. result.m[5] = (axis.y * axis.y) * c1 + c;
  3386. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3387. result.m[7] = 0.0;
  3388. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3389. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3390. result.m[10] = (axis.z * axis.z) * c1 + c;
  3391. result.m[11] = 0.0;
  3392. result.m[15] = 1.0;
  3393. result._markAsUpdated();
  3394. };
  3395. /**
  3396. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3397. */
  3398. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3399. var result = new Matrix();
  3400. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3405. */
  3406. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3407. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3408. this._tempQuaternion.toRotationMatrix(result);
  3409. };
  3410. /**
  3411. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3412. */
  3413. Matrix.Scaling = function (x, y, z) {
  3414. var result = Matrix.Zero();
  3415. Matrix.ScalingToRef(x, y, z, result);
  3416. return result;
  3417. };
  3418. /**
  3419. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3420. */
  3421. Matrix.ScalingToRef = function (x, y, z, result) {
  3422. result.m[0] = x;
  3423. result.m[1] = 0.0;
  3424. result.m[2] = 0.0;
  3425. result.m[3] = 0.0;
  3426. result.m[4] = 0.0;
  3427. result.m[5] = y;
  3428. result.m[6] = 0.0;
  3429. result.m[7] = 0.0;
  3430. result.m[8] = 0.0;
  3431. result.m[9] = 0.0;
  3432. result.m[10] = z;
  3433. result.m[11] = 0.0;
  3434. result.m[12] = 0.0;
  3435. result.m[13] = 0.0;
  3436. result.m[14] = 0.0;
  3437. result.m[15] = 1.0;
  3438. result._markAsUpdated();
  3439. };
  3440. /**
  3441. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3442. */
  3443. Matrix.Translation = function (x, y, z) {
  3444. var result = Matrix.Identity();
  3445. Matrix.TranslationToRef(x, y, z, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3450. */
  3451. Matrix.TranslationToRef = function (x, y, z, result) {
  3452. 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);
  3453. };
  3454. /**
  3455. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3456. */
  3457. Matrix.Lerp = function (startValue, endValue, gradient) {
  3458. var result = Matrix.Zero();
  3459. for (var index = 0; index < 16; index++) {
  3460. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3461. }
  3462. result._markAsUpdated();
  3463. return result;
  3464. };
  3465. /**
  3466. * Returns a new Matrix whose values are computed by :
  3467. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3468. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3469. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3470. */
  3471. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3472. var startScale = new Vector3(0, 0, 0);
  3473. var startRotation = new Quaternion();
  3474. var startTranslation = new Vector3(0, 0, 0);
  3475. startValue.decompose(startScale, startRotation, startTranslation);
  3476. var endScale = new Vector3(0, 0, 0);
  3477. var endRotation = new Quaternion();
  3478. var endTranslation = new Vector3(0, 0, 0);
  3479. endValue.decompose(endScale, endRotation, endTranslation);
  3480. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3481. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3482. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3483. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3484. };
  3485. /**
  3486. * 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".
  3487. * This methods works for a Left-Handed system.
  3488. */
  3489. Matrix.LookAtLH = function (eye, target, up) {
  3490. var result = Matrix.Zero();
  3491. Matrix.LookAtLHToRef(eye, target, up, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * 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".
  3496. * This methods works for a Left-Handed system.
  3497. */
  3498. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3499. // Z axis
  3500. target.subtractToRef(eye, this._zAxis);
  3501. this._zAxis.normalize();
  3502. // X axis
  3503. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3504. if (this._xAxis.lengthSquared() === 0) {
  3505. this._xAxis.x = 1.0;
  3506. }
  3507. else {
  3508. this._xAxis.normalize();
  3509. }
  3510. // Y axis
  3511. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3512. this._yAxis.normalize();
  3513. // Eye angles
  3514. var ex = -Vector3.Dot(this._xAxis, eye);
  3515. var ey = -Vector3.Dot(this._yAxis, eye);
  3516. var ez = -Vector3.Dot(this._zAxis, eye);
  3517. 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);
  3518. };
  3519. /**
  3520. * 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".
  3521. * This methods works for a Right-Handed system.
  3522. */
  3523. Matrix.LookAtRH = function (eye, target, up) {
  3524. var result = Matrix.Zero();
  3525. Matrix.LookAtRHToRef(eye, target, up, result);
  3526. return result;
  3527. };
  3528. /**
  3529. * 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".
  3530. * This methods works for a Left-Handed system.
  3531. */
  3532. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3533. // Z axis
  3534. eye.subtractToRef(target, this._zAxis);
  3535. this._zAxis.normalize();
  3536. // X axis
  3537. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3538. if (this._xAxis.lengthSquared() === 0) {
  3539. this._xAxis.x = 1.0;
  3540. }
  3541. else {
  3542. this._xAxis.normalize();
  3543. }
  3544. // Y axis
  3545. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3546. this._yAxis.normalize();
  3547. // Eye angles
  3548. var ex = -Vector3.Dot(this._xAxis, eye);
  3549. var ey = -Vector3.Dot(this._yAxis, eye);
  3550. var ez = -Vector3.Dot(this._zAxis, eye);
  3551. 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);
  3552. };
  3553. /**
  3554. * 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.
  3555. */
  3556. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3557. var matrix = Matrix.Zero();
  3558. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3559. return matrix;
  3560. };
  3561. /**
  3562. * 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.
  3563. */
  3564. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3565. var n = znear;
  3566. var f = zfar;
  3567. var a = 2.0 / width;
  3568. var b = 2.0 / height;
  3569. var c = 2.0 / (f - n);
  3570. var d = -(f + n) / (f - n);
  3571. 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);
  3572. };
  3573. /**
  3574. * 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.
  3575. */
  3576. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * 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.
  3583. */
  3584. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3585. var n = znear;
  3586. var f = zfar;
  3587. var a = 2.0 / (right - left);
  3588. var b = 2.0 / (top - bottom);
  3589. var c = 2.0 / (f - n);
  3590. var d = -(f + n) / (f - n);
  3591. var i0 = (left + right) / (left - right);
  3592. var i1 = (top + bottom) / (bottom - top);
  3593. 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);
  3594. };
  3595. /**
  3596. * 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.
  3597. */
  3598. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * 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.
  3605. */
  3606. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3607. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3608. result.m[10] *= -1.0;
  3609. };
  3610. /**
  3611. * 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.
  3612. */
  3613. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3614. var matrix = Matrix.Zero();
  3615. var n = znear;
  3616. var f = zfar;
  3617. var a = 2.0 * n / width;
  3618. var b = 2.0 * n / height;
  3619. var c = (f + n) / (f - n);
  3620. var d = -2.0 * f * n / (f - n);
  3621. 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);
  3622. return matrix;
  3623. };
  3624. /**
  3625. * 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.
  3626. */
  3627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3628. var matrix = Matrix.Zero();
  3629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3630. return matrix;
  3631. };
  3632. /**
  3633. * 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.
  3634. */
  3635. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3636. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3637. var n = znear;
  3638. var f = zfar;
  3639. var t = 1.0 / (Math.tan(fov * 0.5));
  3640. var a = isVerticalFovFixed ? (t / aspect) : t;
  3641. var b = isVerticalFovFixed ? t : (t * aspect);
  3642. var c = (f + n) / (f - n);
  3643. var d = -2.0 * f * n / (f - n);
  3644. 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);
  3645. };
  3646. /**
  3647. * 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.
  3648. */
  3649. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3650. var matrix = Matrix.Zero();
  3651. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3652. return matrix;
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3658. //alternatively this could be expressed as:
  3659. // m = PerspectiveFovLHToRef
  3660. // m[10] *= -1.0;
  3661. // m[11] *= -1.0;
  3662. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3663. var n = znear;
  3664. var f = zfar;
  3665. var t = 1.0 / (Math.tan(fov * 0.5));
  3666. var a = isVerticalFovFixed ? (t / aspect) : t;
  3667. var b = isVerticalFovFixed ? t : (t * aspect);
  3668. var c = -(f + n) / (f - n);
  3669. var d = -2 * f * n / (f - n);
  3670. 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);
  3671. };
  3672. /**
  3673. * 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.
  3674. */
  3675. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3676. if (rightHanded === void 0) { rightHanded = false; }
  3677. var rightHandedFactor = rightHanded ? -1 : 1;
  3678. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3679. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3680. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3681. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3682. var xScale = 2.0 / (leftTan + rightTan);
  3683. var yScale = 2.0 / (upTan + downTan);
  3684. result.m[0] = xScale;
  3685. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3686. result.m[5] = yScale;
  3687. result.m[6] = result.m[7] = 0.0;
  3688. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3689. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3690. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3691. result.m[10] = -zfar / (znear - zfar);
  3692. result.m[11] = 1.0 * rightHandedFactor;
  3693. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3694. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3695. // result.m[14] = (znear * zfar) / (znear - zfar);
  3696. result._markAsUpdated();
  3697. };
  3698. /**
  3699. * Returns the final transformation matrix : world * view * projection * viewport
  3700. */
  3701. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3702. var cw = viewport.width;
  3703. var ch = viewport.height;
  3704. var cx = viewport.x;
  3705. var cy = viewport.y;
  3706. 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);
  3707. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3708. };
  3709. /**
  3710. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3711. */
  3712. Matrix.GetAsMatrix2x2 = function (matrix) {
  3713. return new Float32Array([
  3714. matrix.m[0], matrix.m[1],
  3715. matrix.m[4], matrix.m[5]
  3716. ]);
  3717. };
  3718. /**
  3719. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3720. */
  3721. Matrix.GetAsMatrix3x3 = function (matrix) {
  3722. return new Float32Array([
  3723. matrix.m[0], matrix.m[1], matrix.m[2],
  3724. matrix.m[4], matrix.m[5], matrix.m[6],
  3725. matrix.m[8], matrix.m[9], matrix.m[10]
  3726. ]);
  3727. };
  3728. /**
  3729. * Compute the transpose of the passed Matrix.
  3730. * Returns a new Matrix.
  3731. */
  3732. Matrix.Transpose = function (matrix) {
  3733. var result = new Matrix();
  3734. result.m[0] = matrix.m[0];
  3735. result.m[1] = matrix.m[4];
  3736. result.m[2] = matrix.m[8];
  3737. result.m[3] = matrix.m[12];
  3738. result.m[4] = matrix.m[1];
  3739. result.m[5] = matrix.m[5];
  3740. result.m[6] = matrix.m[9];
  3741. result.m[7] = matrix.m[13];
  3742. result.m[8] = matrix.m[2];
  3743. result.m[9] = matrix.m[6];
  3744. result.m[10] = matrix.m[10];
  3745. result.m[11] = matrix.m[14];
  3746. result.m[12] = matrix.m[3];
  3747. result.m[13] = matrix.m[7];
  3748. result.m[14] = matrix.m[11];
  3749. result.m[15] = matrix.m[15];
  3750. return result;
  3751. };
  3752. /**
  3753. * Returns a new Matrix as the reflection matrix across the passed plane.
  3754. */
  3755. Matrix.Reflection = function (plane) {
  3756. var matrix = new Matrix();
  3757. Matrix.ReflectionToRef(plane, matrix);
  3758. return matrix;
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3762. */
  3763. Matrix.ReflectionToRef = function (plane, result) {
  3764. plane.normalize();
  3765. var x = plane.normal.x;
  3766. var y = plane.normal.y;
  3767. var z = plane.normal.z;
  3768. var temp = -2 * x;
  3769. var temp2 = -2 * y;
  3770. var temp3 = -2 * z;
  3771. result.m[0] = (temp * x) + 1;
  3772. result.m[1] = temp2 * x;
  3773. result.m[2] = temp3 * x;
  3774. result.m[3] = 0.0;
  3775. result.m[4] = temp * y;
  3776. result.m[5] = (temp2 * y) + 1;
  3777. result.m[6] = temp3 * y;
  3778. result.m[7] = 0.0;
  3779. result.m[8] = temp * z;
  3780. result.m[9] = temp2 * z;
  3781. result.m[10] = (temp3 * z) + 1;
  3782. result.m[11] = 0.0;
  3783. result.m[12] = temp * plane.d;
  3784. result.m[13] = temp2 * plane.d;
  3785. result.m[14] = temp3 * plane.d;
  3786. result.m[15] = 1.0;
  3787. result._markAsUpdated();
  3788. };
  3789. /**
  3790. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3791. */
  3792. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3793. result.m[0] = xaxis.x;
  3794. result.m[1] = xaxis.y;
  3795. result.m[2] = xaxis.z;
  3796. result.m[3] = 0.0;
  3797. result.m[4] = yaxis.x;
  3798. result.m[5] = yaxis.y;
  3799. result.m[6] = yaxis.z;
  3800. result.m[7] = 0.0;
  3801. result.m[8] = zaxis.x;
  3802. result.m[9] = zaxis.y;
  3803. result.m[10] = zaxis.z;
  3804. result.m[11] = 0.0;
  3805. result.m[12] = 0.0;
  3806. result.m[13] = 0.0;
  3807. result.m[14] = 0.0;
  3808. result.m[15] = 1.0;
  3809. result._markAsUpdated();
  3810. };
  3811. /**
  3812. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3813. */
  3814. Matrix.FromQuaternionToRef = function (quat, result) {
  3815. var xx = quat.x * quat.x;
  3816. var yy = quat.y * quat.y;
  3817. var zz = quat.z * quat.z;
  3818. var xy = quat.x * quat.y;
  3819. var zw = quat.z * quat.w;
  3820. var zx = quat.z * quat.x;
  3821. var yw = quat.y * quat.w;
  3822. var yz = quat.y * quat.z;
  3823. var xw = quat.x * quat.w;
  3824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3825. result.m[1] = 2.0 * (xy + zw);
  3826. result.m[2] = 2.0 * (zx - yw);
  3827. result.m[3] = 0.0;
  3828. result.m[4] = 2.0 * (xy - zw);
  3829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3830. result.m[6] = 2.0 * (yz + xw);
  3831. result.m[7] = 0.0;
  3832. result.m[8] = 2.0 * (zx + yw);
  3833. result.m[9] = 2.0 * (yz - xw);
  3834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3835. result.m[11] = 0.0;
  3836. result.m[12] = 0.0;
  3837. result.m[13] = 0.0;
  3838. result.m[14] = 0.0;
  3839. result.m[15] = 1.0;
  3840. result._markAsUpdated();
  3841. };
  3842. return Matrix;
  3843. }());
  3844. Matrix._tempQuaternion = new Quaternion();
  3845. Matrix._xAxis = Vector3.Zero();
  3846. Matrix._yAxis = Vector3.Zero();
  3847. Matrix._zAxis = Vector3.Zero();
  3848. Matrix._updateFlagSeed = 0;
  3849. BABYLON.Matrix = Matrix;
  3850. var Plane = (function () {
  3851. /**
  3852. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3853. */
  3854. function Plane(a, b, c, d) {
  3855. this.normal = new Vector3(a, b, c);
  3856. this.d = d;
  3857. }
  3858. /**
  3859. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3860. */
  3861. Plane.prototype.asArray = function () {
  3862. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3863. };
  3864. // Methods
  3865. /**
  3866. * Returns a new plane copied from the current Plane.
  3867. */
  3868. Plane.prototype.clone = function () {
  3869. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3870. };
  3871. /**
  3872. * Returns the string "Plane".
  3873. */
  3874. Plane.prototype.getClassName = function () {
  3875. return "Plane";
  3876. };
  3877. /**
  3878. * Returns the Plane hash code.
  3879. */
  3880. Plane.prototype.getHashCode = function () {
  3881. var hash = this.normal.getHashCode();
  3882. hash = (hash * 397) ^ (this.d || 0);
  3883. return hash;
  3884. };
  3885. /**
  3886. * Normalize the current Plane in place.
  3887. * Returns the updated Plane.
  3888. */
  3889. Plane.prototype.normalize = function () {
  3890. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3891. var magnitude = 0.0;
  3892. if (norm !== 0) {
  3893. magnitude = 1.0 / norm;
  3894. }
  3895. this.normal.x *= magnitude;
  3896. this.normal.y *= magnitude;
  3897. this.normal.z *= magnitude;
  3898. this.d *= magnitude;
  3899. return this;
  3900. };
  3901. /**
  3902. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3903. */
  3904. Plane.prototype.transform = function (transformation) {
  3905. var transposedMatrix = Matrix.Transpose(transformation);
  3906. var x = this.normal.x;
  3907. var y = this.normal.y;
  3908. var z = this.normal.z;
  3909. var d = this.d;
  3910. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3911. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3912. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3913. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3914. return new Plane(normalX, normalY, normalZ, finalD);
  3915. };
  3916. /**
  3917. * Returns the dot product (float) of the point coordinates and the plane normal.
  3918. */
  3919. Plane.prototype.dotCoordinate = function (point) {
  3920. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3921. };
  3922. /**
  3923. * Updates the current Plane from the plane defined by the three passed points.
  3924. * Returns the updated Plane.
  3925. */
  3926. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3927. var x1 = point2.x - point1.x;
  3928. var y1 = point2.y - point1.y;
  3929. var z1 = point2.z - point1.z;
  3930. var x2 = point3.x - point1.x;
  3931. var y2 = point3.y - point1.y;
  3932. var z2 = point3.z - point1.z;
  3933. var yz = (y1 * z2) - (z1 * y2);
  3934. var xz = (z1 * x2) - (x1 * z2);
  3935. var xy = (x1 * y2) - (y1 * x2);
  3936. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3937. var invPyth;
  3938. if (pyth !== 0) {
  3939. invPyth = 1.0 / pyth;
  3940. }
  3941. else {
  3942. invPyth = 0.0;
  3943. }
  3944. this.normal.x = yz * invPyth;
  3945. this.normal.y = xz * invPyth;
  3946. this.normal.z = xy * invPyth;
  3947. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3948. return this;
  3949. };
  3950. /**
  3951. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3952. */
  3953. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3954. var dot = Vector3.Dot(this.normal, direction);
  3955. return (dot <= epsilon);
  3956. };
  3957. /**
  3958. * Returns the signed distance (float) from the passed point to the Plane.
  3959. */
  3960. Plane.prototype.signedDistanceTo = function (point) {
  3961. return Vector3.Dot(point, this.normal) + this.d;
  3962. };
  3963. // Statics
  3964. /**
  3965. * Returns a new Plane from the passed array.
  3966. */
  3967. Plane.FromArray = function (array) {
  3968. return new Plane(array[0], array[1], array[2], array[3]);
  3969. };
  3970. /**
  3971. * Returns a new Plane defined by the three passed points.
  3972. */
  3973. Plane.FromPoints = function (point1, point2, point3) {
  3974. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3975. result.copyFromPoints(point1, point2, point3);
  3976. return result;
  3977. };
  3978. /**
  3979. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3980. * Note : the vector "normal" is updated because normalized.
  3981. */
  3982. Plane.FromPositionAndNormal = function (origin, normal) {
  3983. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3984. normal.normalize();
  3985. result.normal = normal;
  3986. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3987. return result;
  3988. };
  3989. /**
  3990. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3991. */
  3992. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3993. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3994. return Vector3.Dot(point, normal) + d;
  3995. };
  3996. return Plane;
  3997. }());
  3998. BABYLON.Plane = Plane;
  3999. var Viewport = (function () {
  4000. /**
  4001. * Creates a Viewport object located at (x, y) and sized (width, height).
  4002. */
  4003. function Viewport(x, y, width, height) {
  4004. this.x = x;
  4005. this.y = y;
  4006. this.width = width;
  4007. this.height = height;
  4008. }
  4009. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  4010. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4011. };
  4012. /**
  4013. * Returns a new Viewport copied from the current one.
  4014. */
  4015. Viewport.prototype.clone = function () {
  4016. return new Viewport(this.x, this.y, this.width, this.height);
  4017. };
  4018. return Viewport;
  4019. }());
  4020. BABYLON.Viewport = Viewport;
  4021. var Frustum = (function () {
  4022. function Frustum() {
  4023. }
  4024. /**
  4025. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4026. */
  4027. Frustum.GetPlanes = function (transform) {
  4028. var frustumPlanes = [];
  4029. for (var index = 0; index < 6; index++) {
  4030. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4031. }
  4032. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4033. return frustumPlanes;
  4034. };
  4035. /**
  4036. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4037. */
  4038. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4039. // Near
  4040. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4041. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4042. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4043. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4044. frustumPlanes[0].normalize();
  4045. // Far
  4046. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4047. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4048. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4049. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4050. frustumPlanes[1].normalize();
  4051. // Left
  4052. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4053. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4054. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4055. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4056. frustumPlanes[2].normalize();
  4057. // Right
  4058. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4059. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4060. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4061. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4062. frustumPlanes[3].normalize();
  4063. // Top
  4064. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4065. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4066. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4067. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4068. frustumPlanes[4].normalize();
  4069. // Bottom
  4070. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4071. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4072. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4073. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4074. frustumPlanes[5].normalize();
  4075. };
  4076. return Frustum;
  4077. }());
  4078. BABYLON.Frustum = Frustum;
  4079. var Space;
  4080. (function (Space) {
  4081. Space[Space["LOCAL"] = 0] = "LOCAL";
  4082. Space[Space["WORLD"] = 1] = "WORLD";
  4083. Space[Space["BONE"] = 2] = "BONE";
  4084. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4085. var Axis = (function () {
  4086. function Axis() {
  4087. }
  4088. return Axis;
  4089. }());
  4090. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4091. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4092. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4093. BABYLON.Axis = Axis;
  4094. ;
  4095. var BezierCurve = (function () {
  4096. function BezierCurve() {
  4097. }
  4098. /**
  4099. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4100. */
  4101. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4102. // Extract X (which is equal to time here)
  4103. var f0 = 1 - 3 * x2 + 3 * x1;
  4104. var f1 = 3 * x2 - 6 * x1;
  4105. var f2 = 3 * x1;
  4106. var refinedT = t;
  4107. for (var i = 0; i < 5; i++) {
  4108. var refinedT2 = refinedT * refinedT;
  4109. var refinedT3 = refinedT2 * refinedT;
  4110. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4111. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4112. refinedT -= (x - t) * slope;
  4113. refinedT = Math.min(1, Math.max(0, refinedT));
  4114. }
  4115. // Resolve cubic bezier for the given x
  4116. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4117. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4118. Math.pow(refinedT, 3);
  4119. };
  4120. return BezierCurve;
  4121. }());
  4122. BABYLON.BezierCurve = BezierCurve;
  4123. var Orientation;
  4124. (function (Orientation) {
  4125. Orientation[Orientation["CW"] = 0] = "CW";
  4126. Orientation[Orientation["CCW"] = 1] = "CCW";
  4127. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4128. var Angle = (function () {
  4129. /**
  4130. * Creates an Angle object of "radians" radians (float).
  4131. */
  4132. function Angle(radians) {
  4133. var _this = this;
  4134. /**
  4135. * Returns the Angle value in degrees (float).
  4136. */
  4137. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4138. /**
  4139. * Returns the Angle value in radians (float).
  4140. */
  4141. this.radians = function () { return _this._radians; };
  4142. this._radians = radians;
  4143. if (this._radians < 0.0)
  4144. this._radians += (2.0 * Math.PI);
  4145. }
  4146. /**
  4147. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4148. */
  4149. Angle.BetweenTwoPoints = function (a, b) {
  4150. var delta = b.subtract(a);
  4151. var theta = Math.atan2(delta.y, delta.x);
  4152. return new Angle(theta);
  4153. };
  4154. /**
  4155. * Returns a new Angle object from the passed float in radians.
  4156. */
  4157. Angle.FromRadians = function (radians) {
  4158. return new Angle(radians);
  4159. };
  4160. /**
  4161. * Returns a new Angle object from the passed float in degrees.
  4162. */
  4163. Angle.FromDegrees = function (degrees) {
  4164. return new Angle(degrees * Math.PI / 180.0);
  4165. };
  4166. return Angle;
  4167. }());
  4168. BABYLON.Angle = Angle;
  4169. var Arc2 = (function () {
  4170. /**
  4171. * Creates an Arc object from the three passed points : start, middle and end.
  4172. */
  4173. function Arc2(startPoint, midPoint, endPoint) {
  4174. this.startPoint = startPoint;
  4175. this.midPoint = midPoint;
  4176. this.endPoint = endPoint;
  4177. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4178. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4179. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4180. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4181. 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);
  4182. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4183. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4184. var a1 = this.startAngle.degrees();
  4185. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4186. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4187. // angles correction
  4188. if (a2 - a1 > +180.0)
  4189. a2 -= 360.0;
  4190. if (a2 - a1 < -180.0)
  4191. a2 += 360.0;
  4192. if (a3 - a2 > +180.0)
  4193. a3 -= 360.0;
  4194. if (a3 - a2 < -180.0)
  4195. a3 += 360.0;
  4196. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4197. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4198. }
  4199. return Arc2;
  4200. }());
  4201. BABYLON.Arc2 = Arc2;
  4202. var Path2 = (function () {
  4203. /**
  4204. * Creates a Path2 object from the starting 2D coordinates x and y.
  4205. */
  4206. function Path2(x, y) {
  4207. this._points = new Array();
  4208. this._length = 0.0;
  4209. this.closed = false;
  4210. this._points.push(new Vector2(x, y));
  4211. }
  4212. /**
  4213. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4214. * Returns the updated Path2.
  4215. */
  4216. Path2.prototype.addLineTo = function (x, y) {
  4217. if (closed) {
  4218. //Tools.Error("cannot add lines to closed paths");
  4219. return this;
  4220. }
  4221. var newPoint = new Vector2(x, y);
  4222. var previousPoint = this._points[this._points.length - 1];
  4223. this._points.push(newPoint);
  4224. this._length += newPoint.subtract(previousPoint).length();
  4225. return this;
  4226. };
  4227. /**
  4228. * 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.
  4229. * Returns the updated Path2.
  4230. */
  4231. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4232. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4233. if (closed) {
  4234. //Tools.Error("cannot add arcs to closed paths");
  4235. return this;
  4236. }
  4237. var startPoint = this._points[this._points.length - 1];
  4238. var midPoint = new Vector2(midX, midY);
  4239. var endPoint = new Vector2(endX, endY);
  4240. var arc = new Arc2(startPoint, midPoint, endPoint);
  4241. var increment = arc.angle.radians() / numberOfSegments;
  4242. if (arc.orientation === Orientation.CW)
  4243. increment *= -1;
  4244. var currentAngle = arc.startAngle.radians() + increment;
  4245. for (var i = 0; i < numberOfSegments; i++) {
  4246. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4247. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4248. this.addLineTo(x, y);
  4249. currentAngle += increment;
  4250. }
  4251. return this;
  4252. };
  4253. /**
  4254. * Closes the Path2.
  4255. * Returns the Path2.
  4256. */
  4257. Path2.prototype.close = function () {
  4258. this.closed = true;
  4259. return this;
  4260. };
  4261. /**
  4262. * Returns the Path2 total length (float).
  4263. */
  4264. Path2.prototype.length = function () {
  4265. var result = this._length;
  4266. if (!this.closed) {
  4267. var lastPoint = this._points[this._points.length - 1];
  4268. var firstPoint = this._points[0];
  4269. result += (firstPoint.subtract(lastPoint).length());
  4270. }
  4271. return result;
  4272. };
  4273. /**
  4274. * Returns the Path2 internal array of points.
  4275. */
  4276. Path2.prototype.getPoints = function () {
  4277. return this._points;
  4278. };
  4279. /**
  4280. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4281. */
  4282. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4283. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4284. //Tools.Error("normalized length position should be between 0 and 1.");
  4285. return Vector2.Zero();
  4286. }
  4287. var lengthPosition = normalizedLengthPosition * this.length();
  4288. var previousOffset = 0;
  4289. for (var i = 0; i < this._points.length; i++) {
  4290. var j = (i + 1) % this._points.length;
  4291. var a = this._points[i];
  4292. var b = this._points[j];
  4293. var bToA = b.subtract(a);
  4294. var nextOffset = (bToA.length() + previousOffset);
  4295. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4296. var dir = bToA.normalize();
  4297. var localOffset = lengthPosition - previousOffset;
  4298. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4299. }
  4300. previousOffset = nextOffset;
  4301. }
  4302. //Tools.Error("internal error");
  4303. return Vector2.Zero();
  4304. };
  4305. /**
  4306. * Returns a new Path2 starting at the coordinates (x, y).
  4307. */
  4308. Path2.StartingAt = function (x, y) {
  4309. return new Path2(x, y);
  4310. };
  4311. return Path2;
  4312. }());
  4313. BABYLON.Path2 = Path2;
  4314. var Path3D = (function () {
  4315. /**
  4316. * new Path3D(path, normal, raw)
  4317. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4318. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4319. * path : an array of Vector3, the curve axis of the Path3D
  4320. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4321. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4322. */
  4323. function Path3D(path, firstNormal, raw) {
  4324. this.path = path;
  4325. this._curve = new Array();
  4326. this._distances = new Array();
  4327. this._tangents = new Array();
  4328. this._normals = new Array();
  4329. this._binormals = new Array();
  4330. for (var p = 0; p < path.length; p++) {
  4331. this._curve[p] = path[p].clone(); // hard copy
  4332. }
  4333. this._raw = raw || false;
  4334. this._compute(firstNormal);
  4335. }
  4336. /**
  4337. * Returns the Path3D array of successive Vector3 designing its curve.
  4338. */
  4339. Path3D.prototype.getCurve = function () {
  4340. return this._curve;
  4341. };
  4342. /**
  4343. * Returns an array populated with tangent vectors on each Path3D curve point.
  4344. */
  4345. Path3D.prototype.getTangents = function () {
  4346. return this._tangents;
  4347. };
  4348. /**
  4349. * Returns an array populated with normal vectors on each Path3D curve point.
  4350. */
  4351. Path3D.prototype.getNormals = function () {
  4352. return this._normals;
  4353. };
  4354. /**
  4355. * Returns an array populated with binormal vectors on each Path3D curve point.
  4356. */
  4357. Path3D.prototype.getBinormals = function () {
  4358. return this._binormals;
  4359. };
  4360. /**
  4361. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4362. */
  4363. Path3D.prototype.getDistances = function () {
  4364. return this._distances;
  4365. };
  4366. /**
  4367. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4368. * Returns the same object updated.
  4369. */
  4370. Path3D.prototype.update = function (path, firstNormal) {
  4371. for (var p = 0; p < path.length; p++) {
  4372. this._curve[p].x = path[p].x;
  4373. this._curve[p].y = path[p].y;
  4374. this._curve[p].z = path[p].z;
  4375. }
  4376. this._compute(firstNormal);
  4377. return this;
  4378. };
  4379. // private function compute() : computes tangents, normals and binormals
  4380. Path3D.prototype._compute = function (firstNormal) {
  4381. var l = this._curve.length;
  4382. // first and last tangents
  4383. this._tangents[0] = this._getFirstNonNullVector(0);
  4384. if (!this._raw) {
  4385. this._tangents[0].normalize();
  4386. }
  4387. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4388. if (!this._raw) {
  4389. this._tangents[l - 1].normalize();
  4390. }
  4391. // normals and binormals at first point : arbitrary vector with _normalVector()
  4392. var tg0 = this._tangents[0];
  4393. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4394. this._normals[0] = pp0;
  4395. if (!this._raw) {
  4396. this._normals[0].normalize();
  4397. }
  4398. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4399. if (!this._raw) {
  4400. this._binormals[0].normalize();
  4401. }
  4402. this._distances[0] = 0.0;
  4403. // normals and binormals : next points
  4404. var prev; // previous vector (segment)
  4405. var cur; // current vector (segment)
  4406. var curTang; // current tangent
  4407. // previous normal
  4408. var prevBinor; // previous binormal
  4409. for (var i = 1; i < l; i++) {
  4410. // tangents
  4411. prev = this._getLastNonNullVector(i);
  4412. if (i < l - 1) {
  4413. cur = this._getFirstNonNullVector(i);
  4414. this._tangents[i] = prev.add(cur);
  4415. this._tangents[i].normalize();
  4416. }
  4417. this._distances[i] = this._distances[i - 1] + prev.length();
  4418. // normals and binormals
  4419. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4420. curTang = this._tangents[i];
  4421. prevBinor = this._binormals[i - 1];
  4422. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4423. if (!this._raw) {
  4424. this._normals[i].normalize();
  4425. }
  4426. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4427. if (!this._raw) {
  4428. this._binormals[i].normalize();
  4429. }
  4430. }
  4431. };
  4432. // private function getFirstNonNullVector(index)
  4433. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4434. Path3D.prototype._getFirstNonNullVector = function (index) {
  4435. var i = 1;
  4436. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4437. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4438. i++;
  4439. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4440. }
  4441. return nNVector;
  4442. };
  4443. // private function getLastNonNullVector(index)
  4444. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4445. Path3D.prototype._getLastNonNullVector = function (index) {
  4446. var i = 1;
  4447. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4448. while (nLVector.length() === 0 && index > i + 1) {
  4449. i++;
  4450. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4451. }
  4452. return nLVector;
  4453. };
  4454. // private function normalVector(v0, vt, va) :
  4455. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4456. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4457. Path3D.prototype._normalVector = function (v0, vt, va) {
  4458. var normal0;
  4459. var tgl = vt.length();
  4460. if (tgl === 0.0) {
  4461. tgl = 1.0;
  4462. }
  4463. if (va === undefined || va === null) {
  4464. var point;
  4465. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4466. point = new Vector3(0.0, -1.0, 0.0);
  4467. }
  4468. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4469. point = new Vector3(1.0, 0.0, 0.0);
  4470. }
  4471. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4472. point = new Vector3(0.0, 0.0, 1.0);
  4473. }
  4474. normal0 = Vector3.Cross(vt, point);
  4475. }
  4476. else {
  4477. normal0 = Vector3.Cross(vt, va);
  4478. Vector3.CrossToRef(normal0, vt, normal0);
  4479. }
  4480. normal0.normalize();
  4481. return normal0;
  4482. };
  4483. return Path3D;
  4484. }());
  4485. BABYLON.Path3D = Path3D;
  4486. var Curve3 = (function () {
  4487. /**
  4488. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4489. * A Curve3 is designed from a series of successive Vector3.
  4490. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4491. */
  4492. function Curve3(points) {
  4493. this._length = 0.0;
  4494. this._points = points;
  4495. this._length = this._computeLength(points);
  4496. }
  4497. /**
  4498. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4499. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4500. * @param v1 (Vector3) the control point
  4501. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4502. * @param nbPoints (integer) the wanted number of points in the curve
  4503. */
  4504. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4505. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4506. var bez = new Array();
  4507. var equation = function (t, val0, val1, val2) {
  4508. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4509. return res;
  4510. };
  4511. for (var i = 0; i <= nbPoints; i++) {
  4512. 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)));
  4513. }
  4514. return new Curve3(bez);
  4515. };
  4516. /**
  4517. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4518. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4519. * @param v1 (Vector3) the first control point
  4520. * @param v2 (Vector3) the second control point
  4521. * @param v3 (Vector3) the end point of the Cubic Bezier
  4522. * @param nbPoints (integer) the wanted number of points in the curve
  4523. */
  4524. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4525. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4526. var bez = new Array();
  4527. var equation = function (t, val0, val1, val2, val3) {
  4528. 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;
  4529. return res;
  4530. };
  4531. for (var i = 0; i <= nbPoints; i++) {
  4532. 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)));
  4533. }
  4534. return new Curve3(bez);
  4535. };
  4536. /**
  4537. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4538. * @param p1 (Vector3) the origin point of the Hermite Spline
  4539. * @param t1 (Vector3) the tangent vector at the origin point
  4540. * @param p2 (Vector3) the end point of the Hermite Spline
  4541. * @param t2 (Vector3) the tangent vector at the end point
  4542. * @param nbPoints (integer) the wanted number of points in the curve
  4543. */
  4544. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4545. var hermite = new Array();
  4546. var step = 1.0 / nbPoints;
  4547. for (var i = 0; i <= nbPoints; i++) {
  4548. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4549. }
  4550. return new Curve3(hermite);
  4551. };
  4552. /**
  4553. * Returns a Curve3 object along a CatmullRom Spline curve :
  4554. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4555. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4556. */
  4557. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4558. var totalPoints = new Array();
  4559. totalPoints.push(points[0].clone());
  4560. Array.prototype.push.apply(totalPoints, points);
  4561. totalPoints.push(points[points.length - 1].clone());
  4562. var catmullRom = new Array();
  4563. var step = 1.0 / nbPoints;
  4564. for (var i = 0; i < totalPoints.length - 3; i++) {
  4565. var amount = 0.0;
  4566. for (var c = 0; c < nbPoints; c++) {
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. amount += step;
  4569. }
  4570. }
  4571. i--;
  4572. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4573. return new Curve3(catmullRom);
  4574. };
  4575. /**
  4576. * Returns the Curve3 stored array of successive Vector3
  4577. */
  4578. Curve3.prototype.getPoints = function () {
  4579. return this._points;
  4580. };
  4581. /**
  4582. * Returns the computed length (float) of the curve.
  4583. */
  4584. Curve3.prototype.length = function () {
  4585. return this._length;
  4586. };
  4587. /**
  4588. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4589. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4590. * curveA and curveB keep unchanged.
  4591. */
  4592. Curve3.prototype.continue = function (curve) {
  4593. var lastPoint = this._points[this._points.length - 1];
  4594. var continuedPoints = this._points.slice();
  4595. var curvePoints = curve.getPoints();
  4596. for (var i = 1; i < curvePoints.length; i++) {
  4597. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4598. }
  4599. var continuedCurve = new Curve3(continuedPoints);
  4600. return continuedCurve;
  4601. };
  4602. Curve3.prototype._computeLength = function (path) {
  4603. var l = 0;
  4604. for (var i = 1; i < path.length; i++) {
  4605. l += (path[i].subtract(path[i - 1])).length();
  4606. }
  4607. return l;
  4608. };
  4609. return Curve3;
  4610. }());
  4611. BABYLON.Curve3 = Curve3;
  4612. // SphericalHarmonics
  4613. var SphericalHarmonics = (function () {
  4614. function SphericalHarmonics() {
  4615. this.L00 = Vector3.Zero();
  4616. this.L1_1 = Vector3.Zero();
  4617. this.L10 = Vector3.Zero();
  4618. this.L11 = Vector3.Zero();
  4619. this.L2_2 = Vector3.Zero();
  4620. this.L2_1 = Vector3.Zero();
  4621. this.L20 = Vector3.Zero();
  4622. this.L21 = Vector3.Zero();
  4623. this.L22 = Vector3.Zero();
  4624. }
  4625. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4626. var colorVector = new Vector3(color.r, color.g, color.b);
  4627. var c = colorVector.scale(deltaSolidAngle);
  4628. this.L00 = this.L00.add(c.scale(0.282095));
  4629. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4630. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4631. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4632. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4633. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4634. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4635. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4636. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4637. };
  4638. SphericalHarmonics.prototype.scale = function (scale) {
  4639. this.L00 = this.L00.scale(scale);
  4640. this.L1_1 = this.L1_1.scale(scale);
  4641. this.L10 = this.L10.scale(scale);
  4642. this.L11 = this.L11.scale(scale);
  4643. this.L2_2 = this.L2_2.scale(scale);
  4644. this.L2_1 = this.L2_1.scale(scale);
  4645. this.L20 = this.L20.scale(scale);
  4646. this.L21 = this.L21.scale(scale);
  4647. this.L22 = this.L22.scale(scale);
  4648. };
  4649. return SphericalHarmonics;
  4650. }());
  4651. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4652. // SphericalPolynomial
  4653. var SphericalPolynomial = (function () {
  4654. function SphericalPolynomial() {
  4655. this.x = Vector3.Zero();
  4656. this.y = Vector3.Zero();
  4657. this.z = Vector3.Zero();
  4658. this.xx = Vector3.Zero();
  4659. this.yy = Vector3.Zero();
  4660. this.zz = Vector3.Zero();
  4661. this.xy = Vector3.Zero();
  4662. this.yz = Vector3.Zero();
  4663. this.zx = Vector3.Zero();
  4664. }
  4665. SphericalPolynomial.prototype.addAmbient = function (color) {
  4666. var colorVector = new Vector3(color.r, color.g, color.b);
  4667. this.xx = this.xx.add(colorVector);
  4668. this.yy = this.yy.add(colorVector);
  4669. this.zz = this.zz.add(colorVector);
  4670. };
  4671. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4672. var result = new SphericalPolynomial();
  4673. result.x = harmonics.L11.scale(1.02333);
  4674. result.y = harmonics.L1_1.scale(1.02333);
  4675. result.z = harmonics.L10.scale(1.02333);
  4676. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4677. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4678. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4679. result.yz = harmonics.L2_1.scale(0.858086);
  4680. result.zx = harmonics.L21.scale(0.858086);
  4681. result.xy = harmonics.L2_2.scale(0.858086);
  4682. return result;
  4683. };
  4684. return SphericalPolynomial;
  4685. }());
  4686. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4687. // Vertex formats
  4688. var PositionNormalVertex = (function () {
  4689. function PositionNormalVertex(position, normal) {
  4690. if (position === void 0) { position = Vector3.Zero(); }
  4691. if (normal === void 0) { normal = Vector3.Up(); }
  4692. this.position = position;
  4693. this.normal = normal;
  4694. }
  4695. PositionNormalVertex.prototype.clone = function () {
  4696. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4697. };
  4698. return PositionNormalVertex;
  4699. }());
  4700. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4701. var PositionNormalTextureVertex = (function () {
  4702. function PositionNormalTextureVertex(position, normal, uv) {
  4703. if (position === void 0) { position = Vector3.Zero(); }
  4704. if (normal === void 0) { normal = Vector3.Up(); }
  4705. if (uv === void 0) { uv = Vector2.Zero(); }
  4706. this.position = position;
  4707. this.normal = normal;
  4708. this.uv = uv;
  4709. }
  4710. PositionNormalTextureVertex.prototype.clone = function () {
  4711. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4712. };
  4713. return PositionNormalTextureVertex;
  4714. }());
  4715. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4716. // Temporary pre-allocated objects for engine internal use
  4717. // usage in any internal function :
  4718. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4719. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4720. var Tmp = (function () {
  4721. function Tmp() {
  4722. }
  4723. return Tmp;
  4724. }());
  4725. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4726. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4727. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4728. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4729. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4730. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4731. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4732. Matrix.Zero(), Matrix.Zero(),
  4733. Matrix.Zero(), Matrix.Zero(),
  4734. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4735. BABYLON.Tmp = Tmp;
  4736. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4737. var MathTmp = (function () {
  4738. function MathTmp() {
  4739. }
  4740. return MathTmp;
  4741. }());
  4742. MathTmp.Vector3 = [Vector3.Zero()];
  4743. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4744. MathTmp.Quaternion = [Quaternion.Zero()];
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.math.js.map
  4747. //# sourceMappingURL=babylon.mixins.js.map
  4748. var BABYLON;
  4749. (function (BABYLON) {
  4750. function generateSerializableMember(type, sourceName) {
  4751. return function (target, propertyKey) {
  4752. if (!target.__serializableMembers) {
  4753. target.__serializableMembers = {};
  4754. }
  4755. if (!target.__serializableMembers[propertyKey]) {
  4756. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4757. }
  4758. };
  4759. }
  4760. function generateExpandMember(setCallback, targetKey) {
  4761. return function (target, propertyKey) {
  4762. var key = targetKey || ("_" + propertyKey);
  4763. Object.defineProperty(target, propertyKey, {
  4764. get: function () {
  4765. return this[key];
  4766. },
  4767. set: function (value) {
  4768. if (this[key] === value) {
  4769. return;
  4770. }
  4771. this[key] = value;
  4772. if (setCallback) {
  4773. target[setCallback].apply(this);
  4774. }
  4775. },
  4776. enumerable: true,
  4777. configurable: true
  4778. });
  4779. };
  4780. }
  4781. function expandToProperty(callback, targetKey) {
  4782. return generateExpandMember(callback, targetKey);
  4783. }
  4784. BABYLON.expandToProperty = expandToProperty;
  4785. function serialize(sourceName) {
  4786. return generateSerializableMember(0, sourceName); // value member
  4787. }
  4788. BABYLON.serialize = serialize;
  4789. function serializeAsTexture(sourceName) {
  4790. return generateSerializableMember(1, sourceName); // texture member
  4791. }
  4792. BABYLON.serializeAsTexture = serializeAsTexture;
  4793. function serializeAsColor3(sourceName) {
  4794. return generateSerializableMember(2, sourceName); // color3 member
  4795. }
  4796. BABYLON.serializeAsColor3 = serializeAsColor3;
  4797. function serializeAsFresnelParameters(sourceName) {
  4798. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4799. }
  4800. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4801. function serializeAsVector2(sourceName) {
  4802. return generateSerializableMember(4, sourceName); // vector2 member
  4803. }
  4804. BABYLON.serializeAsVector2 = serializeAsVector2;
  4805. function serializeAsVector3(sourceName) {
  4806. return generateSerializableMember(5, sourceName); // vector3 member
  4807. }
  4808. BABYLON.serializeAsVector3 = serializeAsVector3;
  4809. function serializeAsMeshReference(sourceName) {
  4810. return generateSerializableMember(6, sourceName); // mesh reference member
  4811. }
  4812. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4813. function serializeAsColorCurves(sourceName) {
  4814. return generateSerializableMember(7, sourceName); // color curves
  4815. }
  4816. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4817. var SerializationHelper = (function () {
  4818. function SerializationHelper() {
  4819. }
  4820. SerializationHelper.Serialize = function (entity, serializationObject) {
  4821. if (!serializationObject) {
  4822. serializationObject = {};
  4823. }
  4824. // Tags
  4825. if (BABYLON.Tags) {
  4826. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4827. }
  4828. // Properties
  4829. for (var property in entity.__serializableMembers) {
  4830. var propertyDescriptor = entity.__serializableMembers[property];
  4831. var targetPropertyName = propertyDescriptor.sourceName || property;
  4832. var propertyType = propertyDescriptor.type;
  4833. var sourceProperty = entity[property];
  4834. if (sourceProperty !== undefined && sourceProperty !== null) {
  4835. switch (propertyType) {
  4836. case 0:
  4837. serializationObject[targetPropertyName] = sourceProperty;
  4838. break;
  4839. case 1:
  4840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4841. break;
  4842. case 2:
  4843. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4844. break;
  4845. case 3:
  4846. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4847. break;
  4848. case 4:
  4849. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4850. break;
  4851. case 5:
  4852. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4853. break;
  4854. case 6:
  4855. serializationObject[targetPropertyName] = sourceProperty.id;
  4856. break;
  4857. case 7:
  4858. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4859. break;
  4860. }
  4861. }
  4862. }
  4863. return serializationObject;
  4864. };
  4865. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4866. var destination = creationFunction();
  4867. // Tags
  4868. if (BABYLON.Tags) {
  4869. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4870. }
  4871. // Properties
  4872. for (var property in destination.__serializableMembers) {
  4873. var propertyDescriptor = destination.__serializableMembers[property];
  4874. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4875. var propertyType = propertyDescriptor.type;
  4876. if (sourceProperty !== undefined && sourceProperty !== null) {
  4877. switch (propertyType) {
  4878. case 0:
  4879. destination[property] = sourceProperty;
  4880. break;
  4881. case 1:
  4882. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4883. break;
  4884. case 2:
  4885. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4886. break;
  4887. case 3:
  4888. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4889. break;
  4890. case 4:
  4891. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4892. break;
  4893. case 5:
  4894. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4895. break;
  4896. case 6:
  4897. destination[property] = scene.getLastMeshByID(sourceProperty);
  4898. break;
  4899. case 7:
  4900. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4901. break;
  4902. }
  4903. }
  4904. }
  4905. return destination;
  4906. };
  4907. SerializationHelper.Clone = function (creationFunction, source) {
  4908. var destination = creationFunction();
  4909. // Tags
  4910. if (BABYLON.Tags) {
  4911. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4912. }
  4913. // Properties
  4914. for (var property in destination.__serializableMembers) {
  4915. var propertyDescriptor = destination.__serializableMembers[property];
  4916. var sourceProperty = source[property];
  4917. var propertyType = propertyDescriptor.type;
  4918. if (sourceProperty !== undefined && sourceProperty !== null) {
  4919. switch (propertyType) {
  4920. case 0: // Value
  4921. case 6:
  4922. destination[property] = sourceProperty;
  4923. break;
  4924. case 1: // Texture
  4925. case 2: // Color3
  4926. case 3: // FresnelParameters
  4927. case 4: // Vector2
  4928. case 5: // Vector3
  4929. case 7:
  4930. destination[property] = sourceProperty.clone();
  4931. break;
  4932. }
  4933. }
  4934. }
  4935. return destination;
  4936. };
  4937. return SerializationHelper;
  4938. }());
  4939. BABYLON.SerializationHelper = SerializationHelper;
  4940. })(BABYLON || (BABYLON = {}));
  4941. //# sourceMappingURL=babylon.decorators.js.map
  4942. var BABYLON;
  4943. (function (BABYLON) {
  4944. /**
  4945. * A class serves as a medium between the observable and its observers
  4946. */
  4947. var EventState = (function () {
  4948. /**
  4949. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4950. */
  4951. function EventState(mask, skipNextObservers) {
  4952. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4953. this.initalize(mask, skipNextObservers);
  4954. }
  4955. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4956. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4957. this.mask = mask;
  4958. this.skipNextObservers = skipNextObservers;
  4959. return this;
  4960. };
  4961. return EventState;
  4962. }());
  4963. BABYLON.EventState = EventState;
  4964. /**
  4965. * Represent an Observer registered to a given Observable object.
  4966. */
  4967. var Observer = (function () {
  4968. function Observer(callback, mask) {
  4969. this.callback = callback;
  4970. this.mask = mask;
  4971. }
  4972. return Observer;
  4973. }());
  4974. BABYLON.Observer = Observer;
  4975. /**
  4976. * The Observable class is a simple implementation of the Observable pattern.
  4977. * 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.
  4978. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4979. * 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).
  4980. * 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.
  4981. */
  4982. var Observable = (function () {
  4983. function Observable() {
  4984. this._observers = new Array();
  4985. this._eventState = new EventState(0);
  4986. }
  4987. /**
  4988. * Create a new Observer with the specified callback
  4989. * @param callback the callback that will be executed for that Observer
  4990. * @param mask the mask used to filter observers
  4991. * @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.
  4992. */
  4993. Observable.prototype.add = function (callback, mask, insertFirst) {
  4994. if (mask === void 0) { mask = -1; }
  4995. if (insertFirst === void 0) { insertFirst = false; }
  4996. if (!callback) {
  4997. return null;
  4998. }
  4999. var observer = new Observer(callback, mask);
  5000. if (insertFirst) {
  5001. this._observers.unshift(observer);
  5002. }
  5003. else {
  5004. this._observers.push(observer);
  5005. }
  5006. return observer;
  5007. };
  5008. /**
  5009. * Remove an Observer from the Observable object
  5010. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5011. */
  5012. Observable.prototype.remove = function (observer) {
  5013. var index = this._observers.indexOf(observer);
  5014. if (index !== -1) {
  5015. this._observers.splice(index, 1);
  5016. return true;
  5017. }
  5018. return false;
  5019. };
  5020. /**
  5021. * Remove a callback from the Observable object
  5022. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5023. */
  5024. Observable.prototype.removeCallback = function (callback) {
  5025. for (var index = 0; index < this._observers.length; index++) {
  5026. if (this._observers[index].callback === callback) {
  5027. this._observers.splice(index, 1);
  5028. return true;
  5029. }
  5030. }
  5031. return false;
  5032. };
  5033. /**
  5034. * Notify all Observers by calling their respective callback with the given data
  5035. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5036. * @param eventData
  5037. * @param mask
  5038. */
  5039. Observable.prototype.notifyObservers = function (eventData, mask) {
  5040. if (mask === void 0) { mask = -1; }
  5041. var state = this._eventState;
  5042. state.mask = mask;
  5043. state.skipNextObservers = false;
  5044. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5045. var obs = _a[_i];
  5046. if (obs.mask & mask) {
  5047. obs.callback(eventData, state);
  5048. }
  5049. if (state.skipNextObservers) {
  5050. return false;
  5051. }
  5052. }
  5053. return true;
  5054. };
  5055. /**
  5056. * return true is the Observable has at least one Observer registered
  5057. */
  5058. Observable.prototype.hasObservers = function () {
  5059. return this._observers.length > 0;
  5060. };
  5061. /**
  5062. * Clear the list of observers
  5063. */
  5064. Observable.prototype.clear = function () {
  5065. this._observers = new Array();
  5066. };
  5067. /**
  5068. * Clone the current observable
  5069. */
  5070. Observable.prototype.clone = function () {
  5071. var result = new Observable();
  5072. result._observers = this._observers.slice(0);
  5073. return result;
  5074. };
  5075. /**
  5076. * Does this observable handles observer registered with a given mask
  5077. * @param {number} trigger - the mask to be tested
  5078. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5079. **/
  5080. Observable.prototype.hasSpecificMask = function (mask) {
  5081. if (mask === void 0) { mask = -1; }
  5082. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5083. var obs = _a[_i];
  5084. if (obs.mask & mask && obs.mask === mask) {
  5085. return true;
  5086. }
  5087. }
  5088. return false;
  5089. };
  5090. return Observable;
  5091. }());
  5092. BABYLON.Observable = Observable;
  5093. })(BABYLON || (BABYLON = {}));
  5094. //# sourceMappingURL=babylon.observable.js.map
  5095. var BABYLON;
  5096. (function (BABYLON) {
  5097. var SmartArray = (function () {
  5098. function SmartArray(capacity) {
  5099. this.length = 0;
  5100. this._duplicateId = 0;
  5101. this.data = new Array(capacity);
  5102. this._id = SmartArray._GlobalId++;
  5103. }
  5104. SmartArray.prototype.push = function (value) {
  5105. this.data[this.length++] = value;
  5106. if (this.length > this.data.length) {
  5107. this.data.length *= 2;
  5108. }
  5109. if (!value.__smartArrayFlags) {
  5110. value.__smartArrayFlags = {};
  5111. }
  5112. value.__smartArrayFlags[this._id] = this._duplicateId;
  5113. };
  5114. SmartArray.prototype.forEach = function (func) {
  5115. for (var index = 0; index < this.length; index++) {
  5116. func(this.data[index]);
  5117. }
  5118. };
  5119. SmartArray.prototype.pushNoDuplicate = function (value) {
  5120. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5121. return false;
  5122. }
  5123. this.push(value);
  5124. return true;
  5125. };
  5126. SmartArray.prototype.sort = function (compareFn) {
  5127. this.data.sort(compareFn);
  5128. };
  5129. SmartArray.prototype.reset = function () {
  5130. this.length = 0;
  5131. this._duplicateId++;
  5132. };
  5133. SmartArray.prototype.dispose = function () {
  5134. this.reset();
  5135. this.data.length = 0;
  5136. };
  5137. SmartArray.prototype.concat = function (array) {
  5138. if (array.length === 0) {
  5139. return;
  5140. }
  5141. if (this.length + array.length > this.data.length) {
  5142. this.data.length = (this.length + array.length) * 2;
  5143. }
  5144. for (var index = 0; index < array.length; index++) {
  5145. this.data[this.length++] = (array.data || array)[index];
  5146. }
  5147. };
  5148. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5149. if (array.length === 0) {
  5150. return;
  5151. }
  5152. if (this.length + array.length > this.data.length) {
  5153. this.data.length = (this.length + array.length) * 2;
  5154. }
  5155. for (var index = 0; index < array.length; index++) {
  5156. var item = (array.data || array)[index];
  5157. this.pushNoDuplicate(item);
  5158. }
  5159. };
  5160. SmartArray.prototype.indexOf = function (value) {
  5161. var position = this.data.indexOf(value);
  5162. if (position >= this.length) {
  5163. return -1;
  5164. }
  5165. return position;
  5166. };
  5167. SmartArray.prototype.contains = function (value) {
  5168. return this.data.indexOf(value) !== -1;
  5169. };
  5170. return SmartArray;
  5171. }());
  5172. // Statics
  5173. SmartArray._GlobalId = 0;
  5174. BABYLON.SmartArray = SmartArray;
  5175. })(BABYLON || (BABYLON = {}));
  5176. //# sourceMappingURL=babylon.smartArray.js.map
  5177. var BABYLON;
  5178. (function (BABYLON) {
  5179. // Screenshots
  5180. var screenshotCanvas;
  5181. var cloneValue = function (source, destinationObject) {
  5182. if (!source)
  5183. return null;
  5184. if (source instanceof BABYLON.Mesh) {
  5185. return null;
  5186. }
  5187. if (source instanceof BABYLON.SubMesh) {
  5188. return source.clone(destinationObject);
  5189. }
  5190. else if (source.clone) {
  5191. return source.clone();
  5192. }
  5193. return null;
  5194. };
  5195. var Tools = (function () {
  5196. function Tools() {
  5197. }
  5198. ;
  5199. /**
  5200. * Interpolates between a and b via alpha
  5201. * @param a The lower value (returned when alpha = 0)
  5202. * @param b The upper value (returned when alpha = 1)
  5203. * @param alpha The interpolation-factor
  5204. * @return The mixed value
  5205. */
  5206. Tools.Mix = function (a, b, alpha) {
  5207. return a * (1 - alpha) + b * alpha;
  5208. };
  5209. Tools.Instantiate = function (className) {
  5210. var arr = className.split(".");
  5211. var fn = (window || this);
  5212. for (var i = 0, len = arr.length; i < len; i++) {
  5213. fn = fn[arr[i]];
  5214. }
  5215. if (typeof fn !== "function") {
  5216. return null;
  5217. }
  5218. return fn;
  5219. };
  5220. Tools.SetImmediate = function (action) {
  5221. if (window.setImmediate) {
  5222. window.setImmediate(action);
  5223. }
  5224. else {
  5225. setTimeout(action, 1);
  5226. }
  5227. };
  5228. Tools.IsExponentOfTwo = function (value) {
  5229. var count = 1;
  5230. do {
  5231. count *= 2;
  5232. } while (count < value);
  5233. return count === value;
  5234. };
  5235. /**
  5236. * Find the next highest power of two.
  5237. * @param x Number to start search from.
  5238. * @return Next highest power of two.
  5239. */
  5240. Tools.CeilingPOT = function (x) {
  5241. x--;
  5242. x |= x >> 1;
  5243. x |= x >> 2;
  5244. x |= x >> 4;
  5245. x |= x >> 8;
  5246. x |= x >> 16;
  5247. x++;
  5248. return x;
  5249. };
  5250. /**
  5251. * Find the next lowest power of two.
  5252. * @param x Number to start search from.
  5253. * @return Next lowest power of two.
  5254. */
  5255. Tools.FloorPOT = function (x) {
  5256. x = x | (x >> 1);
  5257. x = x | (x >> 2);
  5258. x = x | (x >> 4);
  5259. x = x | (x >> 8);
  5260. x = x | (x >> 16);
  5261. return x - (x >> 1);
  5262. };
  5263. /**
  5264. * Find the nearest power of two.
  5265. * @param x Number to start search from.
  5266. * @return Next nearest power of two.
  5267. */
  5268. Tools.NearestPOT = function (x) {
  5269. var c = Tools.CeilingPOT(x);
  5270. var f = Tools.FloorPOT(x);
  5271. return (c - x) > (x - f) ? f : c;
  5272. };
  5273. Tools.GetExponentOfTwo = function (value, max, mode) {
  5274. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5275. var pot;
  5276. switch (mode) {
  5277. case BABYLON.Engine.SCALEMODE_FLOOR:
  5278. pot = Tools.FloorPOT(value);
  5279. break;
  5280. case BABYLON.Engine.SCALEMODE_NEAREST:
  5281. pot = Tools.NearestPOT(value);
  5282. break;
  5283. case BABYLON.Engine.SCALEMODE_CEILING:
  5284. pot = Tools.CeilingPOT(value);
  5285. break;
  5286. }
  5287. return Math.min(pot, max);
  5288. };
  5289. Tools.GetFilename = function (path) {
  5290. var index = path.lastIndexOf("/");
  5291. if (index < 0)
  5292. return path;
  5293. return path.substring(index + 1);
  5294. };
  5295. Tools.GetDOMTextContent = function (element) {
  5296. var result = "";
  5297. var child = element.firstChild;
  5298. while (child) {
  5299. if (child.nodeType === 3) {
  5300. result += child.textContent;
  5301. }
  5302. child = child.nextSibling;
  5303. }
  5304. return result;
  5305. };
  5306. Tools.ToDegrees = function (angle) {
  5307. return angle * 180 / Math.PI;
  5308. };
  5309. Tools.ToRadians = function (angle) {
  5310. return angle * Math.PI / 180;
  5311. };
  5312. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5313. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5314. var output = "";
  5315. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5316. var i = 0;
  5317. var bytes = new Uint8Array(buffer);
  5318. while (i < bytes.length) {
  5319. chr1 = bytes[i++];
  5320. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5321. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5322. enc1 = chr1 >> 2;
  5323. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5324. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5325. enc4 = chr3 & 63;
  5326. if (isNaN(chr2)) {
  5327. enc3 = enc4 = 64;
  5328. }
  5329. else if (isNaN(chr3)) {
  5330. enc4 = 64;
  5331. }
  5332. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5333. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5334. }
  5335. return "data:image/png;base64," + output;
  5336. };
  5337. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5338. if (bias === void 0) { bias = null; }
  5339. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5340. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5341. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5342. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5343. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5344. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5345. }
  5346. if (bias) {
  5347. minimum.x -= minimum.x * bias.x + bias.y;
  5348. minimum.y -= minimum.y * bias.x + bias.y;
  5349. minimum.z -= minimum.z * bias.x + bias.y;
  5350. maximum.x += maximum.x * bias.x + bias.y;
  5351. maximum.y += maximum.y * bias.x + bias.y;
  5352. maximum.z += maximum.z * bias.x + bias.y;
  5353. }
  5354. return {
  5355. minimum: minimum,
  5356. maximum: maximum
  5357. };
  5358. };
  5359. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5360. if (bias === void 0) { bias = null; }
  5361. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5362. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5363. if (!stride) {
  5364. stride = 3;
  5365. }
  5366. for (var index = start; index < start + count; index++) {
  5367. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5368. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5369. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5370. }
  5371. if (bias) {
  5372. minimum.x -= minimum.x * bias.x + bias.y;
  5373. minimum.y -= minimum.y * bias.x + bias.y;
  5374. minimum.z -= minimum.z * bias.x + bias.y;
  5375. maximum.x += maximum.x * bias.x + bias.y;
  5376. maximum.y += maximum.y * bias.x + bias.y;
  5377. maximum.z += maximum.z * bias.x + bias.y;
  5378. }
  5379. return {
  5380. minimum: minimum,
  5381. maximum: maximum
  5382. };
  5383. };
  5384. Tools.Vector2ArrayFeeder = function (array) {
  5385. return function (index) {
  5386. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5387. var length = isFloatArray ? array.length / 2 : array.length;
  5388. if (index >= length) {
  5389. return null;
  5390. }
  5391. if (isFloatArray) {
  5392. var fa = array;
  5393. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5394. }
  5395. var a = array;
  5396. return a[index];
  5397. };
  5398. };
  5399. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5400. if (bias === void 0) { bias = null; }
  5401. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5402. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5403. var i = 0;
  5404. var cur = feeder(i++);
  5405. while (cur) {
  5406. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5407. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5408. cur = feeder(i++);
  5409. }
  5410. if (bias) {
  5411. minimum.x -= minimum.x * bias.x + bias.y;
  5412. minimum.y -= minimum.y * bias.x + bias.y;
  5413. maximum.x += maximum.x * bias.x + bias.y;
  5414. maximum.y += maximum.y * bias.x + bias.y;
  5415. }
  5416. return {
  5417. minimum: minimum,
  5418. maximum: maximum
  5419. };
  5420. };
  5421. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5422. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5423. return undefined;
  5424. return Array.isArray(obj) ? obj : [obj];
  5425. };
  5426. // Misc.
  5427. Tools.GetPointerPrefix = function () {
  5428. var eventPrefix = "pointer";
  5429. // Check if pointer events are supported
  5430. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5431. eventPrefix = "mouse";
  5432. }
  5433. return eventPrefix;
  5434. };
  5435. /**
  5436. * @param func - the function to be called
  5437. * @param requester - the object that will request the next frame. Falls back to window.
  5438. */
  5439. Tools.QueueNewFrame = function (func, requester) {
  5440. if (requester === void 0) { requester = window; }
  5441. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5442. /*if(requester.isPresenting) {
  5443. return;
  5444. } else*/ if (requester.requestAnimationFrame)
  5445. requester.requestAnimationFrame(func);
  5446. else if (requester.msRequestAnimationFrame)
  5447. requester.msRequestAnimationFrame(func);
  5448. else if (requester.webkitRequestAnimationFrame)
  5449. requester.webkitRequestAnimationFrame(func);
  5450. else if (requester.mozRequestAnimationFrame)
  5451. requester.mozRequestAnimationFrame(func);
  5452. else if (requester.oRequestAnimationFrame)
  5453. requester.oRequestAnimationFrame(func);
  5454. else {
  5455. window.setTimeout(func, 16);
  5456. }
  5457. };
  5458. Tools.RequestFullscreen = function (element) {
  5459. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5460. if (!requestFunction)
  5461. return;
  5462. requestFunction.call(element);
  5463. };
  5464. Tools.ExitFullscreen = function () {
  5465. if (document.exitFullscreen) {
  5466. document.exitFullscreen();
  5467. }
  5468. else if (document.mozCancelFullScreen) {
  5469. document.mozCancelFullScreen();
  5470. }
  5471. else if (document.webkitCancelFullScreen) {
  5472. document.webkitCancelFullScreen();
  5473. }
  5474. else if (document.msCancelFullScreen) {
  5475. document.msCancelFullScreen();
  5476. }
  5477. };
  5478. Tools.SetCorsBehavior = function (url, img) {
  5479. if (Tools.CorsBehavior) {
  5480. switch (typeof (Tools.CorsBehavior)) {
  5481. case "function":
  5482. var result = Tools.CorsBehavior(url);
  5483. if (result) {
  5484. img.crossOrigin = result;
  5485. }
  5486. break;
  5487. case "string":
  5488. default:
  5489. img.crossOrigin = Tools.CorsBehavior;
  5490. break;
  5491. }
  5492. }
  5493. };
  5494. // External files
  5495. Tools.CleanUrl = function (url) {
  5496. url = url.replace(/#/mg, "%23");
  5497. return url;
  5498. };
  5499. Tools.LoadImage = function (url, onload, onerror, database) {
  5500. if (url instanceof ArrayBuffer) {
  5501. url = Tools.EncodeArrayBufferTobase64(url);
  5502. }
  5503. url = Tools.CleanUrl(url);
  5504. var img = new Image();
  5505. if (url.substr(0, 5) !== "data:") {
  5506. Tools.SetCorsBehavior(url, img);
  5507. }
  5508. img.onload = function () {
  5509. onload(img);
  5510. };
  5511. img.onerror = function (err) {
  5512. Tools.Error("Error while trying to load image: " + url);
  5513. if (Tools.UseFallbackTexture) {
  5514. img.src = Tools.fallbackTexture;
  5515. onload(img);
  5516. }
  5517. else {
  5518. onerror();
  5519. }
  5520. };
  5521. var noIndexedDB = function () {
  5522. img.src = url;
  5523. };
  5524. var loadFromIndexedDB = function () {
  5525. database.loadImageFromDB(url, img);
  5526. };
  5527. //ANY database to do!
  5528. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5529. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5530. }
  5531. else {
  5532. if (url.indexOf("file:") !== 0) {
  5533. noIndexedDB();
  5534. }
  5535. else {
  5536. var textureName = url.substring(5).toLowerCase();
  5537. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5538. try {
  5539. var blobURL;
  5540. try {
  5541. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5542. }
  5543. catch (ex) {
  5544. // Chrome doesn't support oneTimeOnly parameter
  5545. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5546. }
  5547. img.src = blobURL;
  5548. }
  5549. catch (e) {
  5550. img.src = null;
  5551. }
  5552. }
  5553. else {
  5554. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5555. img.src = Tools.fallbackTexture;
  5556. }
  5557. }
  5558. }
  5559. return img;
  5560. };
  5561. //ANY
  5562. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5563. url = Tools.CleanUrl(url);
  5564. var noIndexedDB = function () {
  5565. var request = new XMLHttpRequest();
  5566. var loadUrl = Tools.BaseUrl + url;
  5567. request.open('GET', loadUrl, true);
  5568. if (useArrayBuffer) {
  5569. request.responseType = "arraybuffer";
  5570. }
  5571. request.onprogress = progressCallBack;
  5572. request.onreadystatechange = function () {
  5573. // In case of undefined state in some browsers.
  5574. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5575. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5576. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5577. callback(!useArrayBuffer ? request.responseText : request.response);
  5578. }
  5579. else {
  5580. if (onError) {
  5581. onError(request);
  5582. }
  5583. else {
  5584. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5585. }
  5586. }
  5587. }
  5588. };
  5589. request.send(null);
  5590. };
  5591. var loadFromIndexedDB = function () {
  5592. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5593. };
  5594. if (url.indexOf("file:") !== -1) {
  5595. var fileName = url.substring(5).toLowerCase();
  5596. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5597. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5598. }
  5599. else {
  5600. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5601. }
  5602. }
  5603. else {
  5604. // Caching all files
  5605. if (database && database.enableSceneOffline) {
  5606. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5607. }
  5608. else {
  5609. noIndexedDB();
  5610. }
  5611. }
  5612. };
  5613. /**
  5614. * Load a script (identified by an url). When the url returns, the
  5615. * content of this file is added into a new script element, attached to the DOM (body element)
  5616. */
  5617. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5618. var head = document.getElementsByTagName('head')[0];
  5619. var script = document.createElement('script');
  5620. script.type = 'text/javascript';
  5621. script.src = scriptUrl;
  5622. var self = this;
  5623. script.onload = function () {
  5624. if (onSuccess) {
  5625. onSuccess();
  5626. }
  5627. };
  5628. script.onerror = function () {
  5629. if (onError) {
  5630. onError();
  5631. }
  5632. };
  5633. head.appendChild(script);
  5634. };
  5635. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5636. var reader = new FileReader();
  5637. reader.onload = function (e) {
  5638. //target doesn't have result from ts 1.3
  5639. callback(e.target['result']);
  5640. };
  5641. reader.onprogress = progressCallback;
  5642. reader.readAsDataURL(fileToLoad);
  5643. };
  5644. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5645. var reader = new FileReader();
  5646. reader.onerror = function (e) {
  5647. Tools.Log("Error while reading file: " + fileToLoad.name);
  5648. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5649. };
  5650. reader.onload = function (e) {
  5651. //target doesn't have result from ts 1.3
  5652. callback(e.target['result']);
  5653. };
  5654. reader.onprogress = progressCallBack;
  5655. if (!useArrayBuffer) {
  5656. // Asynchronous read
  5657. reader.readAsText(fileToLoad);
  5658. }
  5659. else {
  5660. reader.readAsArrayBuffer(fileToLoad);
  5661. }
  5662. };
  5663. //returns a downloadable url to a file content.
  5664. Tools.FileAsURL = function (content) {
  5665. var fileBlob = new Blob([content]);
  5666. var url = window.URL || window.webkitURL;
  5667. var link = url.createObjectURL(fileBlob);
  5668. return link;
  5669. };
  5670. // Misc.
  5671. Tools.Format = function (value, decimals) {
  5672. if (decimals === void 0) { decimals = 2; }
  5673. return value.toFixed(decimals);
  5674. };
  5675. Tools.CheckExtends = function (v, min, max) {
  5676. if (v.x < min.x)
  5677. min.x = v.x;
  5678. if (v.y < min.y)
  5679. min.y = v.y;
  5680. if (v.z < min.z)
  5681. min.z = v.z;
  5682. if (v.x > max.x)
  5683. max.x = v.x;
  5684. if (v.y > max.y)
  5685. max.y = v.y;
  5686. if (v.z > max.z)
  5687. max.z = v.z;
  5688. };
  5689. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5690. for (var prop in source) {
  5691. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5692. continue;
  5693. }
  5694. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5695. continue;
  5696. }
  5697. var sourceValue = source[prop];
  5698. var typeOfSourceValue = typeof sourceValue;
  5699. if (typeOfSourceValue === "function") {
  5700. continue;
  5701. }
  5702. if (typeOfSourceValue === "object") {
  5703. if (sourceValue instanceof Array) {
  5704. destination[prop] = [];
  5705. if (sourceValue.length > 0) {
  5706. if (typeof sourceValue[0] == "object") {
  5707. for (var index = 0; index < sourceValue.length; index++) {
  5708. var clonedValue = cloneValue(sourceValue[index], destination);
  5709. if (destination[prop].indexOf(clonedValue) === -1) {
  5710. destination[prop].push(clonedValue);
  5711. }
  5712. }
  5713. }
  5714. else {
  5715. destination[prop] = sourceValue.slice(0);
  5716. }
  5717. }
  5718. }
  5719. else {
  5720. destination[prop] = cloneValue(sourceValue, destination);
  5721. }
  5722. }
  5723. else {
  5724. destination[prop] = sourceValue;
  5725. }
  5726. }
  5727. };
  5728. Tools.IsEmpty = function (obj) {
  5729. for (var i in obj) {
  5730. return false;
  5731. }
  5732. return true;
  5733. };
  5734. Tools.RegisterTopRootEvents = function (events) {
  5735. for (var index = 0; index < events.length; index++) {
  5736. var event = events[index];
  5737. window.addEventListener(event.name, event.handler, false);
  5738. try {
  5739. if (window.parent) {
  5740. window.parent.addEventListener(event.name, event.handler, false);
  5741. }
  5742. }
  5743. catch (e) {
  5744. // Silently fails...
  5745. }
  5746. }
  5747. };
  5748. Tools.UnregisterTopRootEvents = function (events) {
  5749. for (var index = 0; index < events.length; index++) {
  5750. var event = events[index];
  5751. window.removeEventListener(event.name, event.handler);
  5752. try {
  5753. if (window.parent) {
  5754. window.parent.removeEventListener(event.name, event.handler);
  5755. }
  5756. }
  5757. catch (e) {
  5758. // Silently fails...
  5759. }
  5760. }
  5761. };
  5762. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5763. if (mimeType === void 0) { mimeType = "image/png"; }
  5764. // Read the contents of the framebuffer
  5765. var numberOfChannelsByLine = width * 4;
  5766. var halfHeight = height / 2;
  5767. //Reading datas from WebGL
  5768. var data = engine.readPixels(0, 0, width, height);
  5769. //To flip image on Y axis.
  5770. for (var i = 0; i < halfHeight; i++) {
  5771. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5772. var currentCell = j + i * numberOfChannelsByLine;
  5773. var targetLine = height - i - 1;
  5774. var targetCell = j + targetLine * numberOfChannelsByLine;
  5775. var temp = data[currentCell];
  5776. data[currentCell] = data[targetCell];
  5777. data[targetCell] = temp;
  5778. }
  5779. }
  5780. // Create a 2D canvas to store the result
  5781. if (!screenshotCanvas) {
  5782. screenshotCanvas = document.createElement('canvas');
  5783. }
  5784. screenshotCanvas.width = width;
  5785. screenshotCanvas.height = height;
  5786. var context = screenshotCanvas.getContext('2d');
  5787. // Copy the pixels to a 2D canvas
  5788. var imageData = context.createImageData(width, height);
  5789. var castData = (imageData.data);
  5790. castData.set(data);
  5791. context.putImageData(imageData, 0, 0);
  5792. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5793. };
  5794. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5795. if (mimeType === void 0) { mimeType = "image/png"; }
  5796. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5797. if (successCallback) {
  5798. successCallback(base64Image);
  5799. }
  5800. else {
  5801. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5802. if (("download" in document.createElement("a"))) {
  5803. var a = window.document.createElement("a");
  5804. a.href = base64Image;
  5805. var date = new Date();
  5806. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5807. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5808. window.document.body.appendChild(a);
  5809. a.addEventListener("click", function () {
  5810. a.parentElement.removeChild(a);
  5811. });
  5812. a.click();
  5813. //Or opening a new tab with the image if it is not possible to automatically start download.
  5814. }
  5815. else {
  5816. var newWindow = window.open("");
  5817. var img = newWindow.document.createElement("img");
  5818. img.src = base64Image;
  5819. newWindow.document.body.appendChild(img);
  5820. }
  5821. }
  5822. };
  5823. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5824. if (mimeType === void 0) { mimeType = "image/png"; }
  5825. var width;
  5826. var height;
  5827. // If a precision value is specified
  5828. if (size.precision) {
  5829. width = Math.round(engine.getRenderWidth() * size.precision);
  5830. height = Math.round(width / engine.getAspectRatio(camera));
  5831. }
  5832. else if (size.width && size.height) {
  5833. width = size.width;
  5834. height = size.height;
  5835. }
  5836. else if (size.width && !size.height) {
  5837. width = size.width;
  5838. height = Math.round(width / engine.getAspectRatio(camera));
  5839. }
  5840. else if (size.height && !size.width) {
  5841. height = size.height;
  5842. width = Math.round(height * engine.getAspectRatio(camera));
  5843. }
  5844. else if (!isNaN(size)) {
  5845. height = size;
  5846. width = size;
  5847. }
  5848. else {
  5849. Tools.Error("Invalid 'size' parameter !");
  5850. return;
  5851. }
  5852. if (!screenshotCanvas) {
  5853. screenshotCanvas = document.createElement('canvas');
  5854. }
  5855. screenshotCanvas.width = width;
  5856. screenshotCanvas.height = height;
  5857. var renderContext = screenshotCanvas.getContext("2d");
  5858. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5859. var newWidth = width;
  5860. var newHeight = newWidth / ratio;
  5861. if (newHeight > height) {
  5862. newHeight = height;
  5863. newWidth = newHeight * ratio;
  5864. }
  5865. var offsetX = Math.max(0, width - newWidth) / 2;
  5866. var offsetY = Math.max(0, height - newHeight) / 2;
  5867. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5868. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5869. };
  5870. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5871. if (mimeType === void 0) { mimeType = "image/png"; }
  5872. if (samples === void 0) { samples = 1; }
  5873. var width;
  5874. var height;
  5875. //If a precision value is specified
  5876. if (size.precision) {
  5877. width = Math.round(engine.getRenderWidth() * size.precision);
  5878. height = Math.round(width / engine.getAspectRatio(camera));
  5879. size = { width: width, height: height };
  5880. }
  5881. else if (size.width && size.height) {
  5882. width = size.width;
  5883. height = size.height;
  5884. }
  5885. else if (size.width && !size.height) {
  5886. width = size.width;
  5887. height = Math.round(width / engine.getAspectRatio(camera));
  5888. size = { width: width, height: height };
  5889. }
  5890. else if (size.height && !size.width) {
  5891. height = size.height;
  5892. width = Math.round(height * engine.getAspectRatio(camera));
  5893. size = { width: width, height: height };
  5894. }
  5895. else if (!isNaN(size)) {
  5896. height = size;
  5897. width = size;
  5898. }
  5899. else {
  5900. Tools.Error("Invalid 'size' parameter !");
  5901. return;
  5902. }
  5903. var scene = camera.getScene();
  5904. var previousCamera = null;
  5905. if (scene.activeCamera !== camera) {
  5906. previousCamera = scene.activeCamera;
  5907. scene.activeCamera = camera;
  5908. }
  5909. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5910. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5911. texture.renderList = scene.meshes;
  5912. texture.samples = samples;
  5913. texture.onAfterRenderObservable.add(function () {
  5914. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5915. });
  5916. scene.incrementRenderId();
  5917. scene.resetCachedMaterial();
  5918. texture.render(true);
  5919. texture.dispose();
  5920. if (previousCamera) {
  5921. scene.activeCamera = previousCamera;
  5922. }
  5923. camera.getProjectionMatrix(true); // Force cache refresh;
  5924. };
  5925. // XHR response validator for local file scenario
  5926. Tools.ValidateXHRData = function (xhr, dataType) {
  5927. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5928. if (dataType === void 0) { dataType = 7; }
  5929. try {
  5930. if (dataType & 1) {
  5931. if (xhr.responseText && xhr.responseText.length > 0) {
  5932. return true;
  5933. }
  5934. else if (dataType === 1) {
  5935. return false;
  5936. }
  5937. }
  5938. if (dataType & 2) {
  5939. // Check header width and height since there is no "TGA" magic number
  5940. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5941. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5942. return true;
  5943. }
  5944. else if (dataType === 2) {
  5945. return false;
  5946. }
  5947. }
  5948. if (dataType & 4) {
  5949. // Check for the "DDS" magic number
  5950. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5951. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5952. return true;
  5953. }
  5954. else {
  5955. return false;
  5956. }
  5957. }
  5958. }
  5959. catch (e) {
  5960. // Global protection
  5961. }
  5962. return false;
  5963. };
  5964. /**
  5965. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5966. * Be aware Math.random() could cause collisions, but:
  5967. * "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"
  5968. */
  5969. Tools.RandomId = function () {
  5970. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5971. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5972. return v.toString(16);
  5973. });
  5974. };
  5975. Object.defineProperty(Tools, "NoneLogLevel", {
  5976. get: function () {
  5977. return Tools._NoneLogLevel;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. Object.defineProperty(Tools, "MessageLogLevel", {
  5983. get: function () {
  5984. return Tools._MessageLogLevel;
  5985. },
  5986. enumerable: true,
  5987. configurable: true
  5988. });
  5989. Object.defineProperty(Tools, "WarningLogLevel", {
  5990. get: function () {
  5991. return Tools._WarningLogLevel;
  5992. },
  5993. enumerable: true,
  5994. configurable: true
  5995. });
  5996. Object.defineProperty(Tools, "ErrorLogLevel", {
  5997. get: function () {
  5998. return Tools._ErrorLogLevel;
  5999. },
  6000. enumerable: true,
  6001. configurable: true
  6002. });
  6003. Object.defineProperty(Tools, "AllLogLevel", {
  6004. get: function () {
  6005. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Tools._AddLogEntry = function (entry) {
  6011. Tools._LogCache = entry + Tools._LogCache;
  6012. if (Tools.OnNewCacheEntry) {
  6013. Tools.OnNewCacheEntry(entry);
  6014. }
  6015. };
  6016. Tools._FormatMessage = function (message) {
  6017. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6018. var date = new Date();
  6019. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6020. };
  6021. Tools._LogDisabled = function (message) {
  6022. // nothing to do
  6023. };
  6024. Tools._LogEnabled = function (message) {
  6025. var formattedMessage = Tools._FormatMessage(message);
  6026. console.log("BJS - " + formattedMessage);
  6027. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6028. Tools._AddLogEntry(entry);
  6029. };
  6030. Tools._WarnDisabled = function (message) {
  6031. // nothing to do
  6032. };
  6033. Tools._WarnEnabled = function (message) {
  6034. var formattedMessage = Tools._FormatMessage(message);
  6035. console.warn("BJS - " + formattedMessage);
  6036. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6037. Tools._AddLogEntry(entry);
  6038. };
  6039. Tools._ErrorDisabled = function (message) {
  6040. // nothing to do
  6041. };
  6042. Tools._ErrorEnabled = function (message) {
  6043. Tools.errorsCount++;
  6044. var formattedMessage = Tools._FormatMessage(message);
  6045. console.error("BJS - " + formattedMessage);
  6046. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6047. Tools._AddLogEntry(entry);
  6048. };
  6049. Object.defineProperty(Tools, "LogCache", {
  6050. get: function () {
  6051. return Tools._LogCache;
  6052. },
  6053. enumerable: true,
  6054. configurable: true
  6055. });
  6056. Tools.ClearLogCache = function () {
  6057. Tools._LogCache = "";
  6058. Tools.errorsCount = 0;
  6059. };
  6060. Object.defineProperty(Tools, "LogLevels", {
  6061. set: function (level) {
  6062. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6063. Tools.Log = Tools._LogEnabled;
  6064. }
  6065. else {
  6066. Tools.Log = Tools._LogDisabled;
  6067. }
  6068. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6069. Tools.Warn = Tools._WarnEnabled;
  6070. }
  6071. else {
  6072. Tools.Warn = Tools._WarnDisabled;
  6073. }
  6074. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6075. Tools.Error = Tools._ErrorEnabled;
  6076. }
  6077. else {
  6078. Tools.Error = Tools._ErrorDisabled;
  6079. }
  6080. },
  6081. enumerable: true,
  6082. configurable: true
  6083. });
  6084. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6085. get: function () {
  6086. return Tools._PerformanceNoneLogLevel;
  6087. },
  6088. enumerable: true,
  6089. configurable: true
  6090. });
  6091. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6092. get: function () {
  6093. return Tools._PerformanceUserMarkLogLevel;
  6094. },
  6095. enumerable: true,
  6096. configurable: true
  6097. });
  6098. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6099. get: function () {
  6100. return Tools._PerformanceConsoleLogLevel;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6106. set: function (level) {
  6107. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6108. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6109. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6110. return;
  6111. }
  6112. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6113. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6114. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6115. return;
  6116. }
  6117. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6118. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6124. };
  6125. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6126. };
  6127. Tools._StartUserMark = function (counterName, condition) {
  6128. if (condition === void 0) { condition = true; }
  6129. if (!condition || !Tools._performance.mark) {
  6130. return;
  6131. }
  6132. Tools._performance.mark(counterName + "-Begin");
  6133. };
  6134. Tools._EndUserMark = function (counterName, condition) {
  6135. if (condition === void 0) { condition = true; }
  6136. if (!condition || !Tools._performance.mark) {
  6137. return;
  6138. }
  6139. Tools._performance.mark(counterName + "-End");
  6140. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6141. };
  6142. Tools._StartPerformanceConsole = function (counterName, condition) {
  6143. if (condition === void 0) { condition = true; }
  6144. if (!condition) {
  6145. return;
  6146. }
  6147. Tools._StartUserMark(counterName, condition);
  6148. if (console.time) {
  6149. console.time(counterName);
  6150. }
  6151. };
  6152. Tools._EndPerformanceConsole = function (counterName, condition) {
  6153. if (condition === void 0) { condition = true; }
  6154. if (!condition) {
  6155. return;
  6156. }
  6157. Tools._EndUserMark(counterName, condition);
  6158. if (console.time) {
  6159. console.timeEnd(counterName);
  6160. }
  6161. };
  6162. Object.defineProperty(Tools, "Now", {
  6163. get: function () {
  6164. if (window.performance && window.performance.now) {
  6165. return window.performance.now();
  6166. }
  6167. return new Date().getTime();
  6168. },
  6169. enumerable: true,
  6170. configurable: true
  6171. });
  6172. /**
  6173. * This method will return the name of the class used to create the instance of the given object.
  6174. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6175. * @param object the object to get the class name from
  6176. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6177. */
  6178. Tools.getClassName = function (object, isType) {
  6179. if (isType === void 0) { isType = false; }
  6180. var name = null;
  6181. if (!isType && object.getClassName) {
  6182. name = object.getClassName();
  6183. }
  6184. else {
  6185. if (object instanceof Object) {
  6186. var classObj = isType ? object : Object.getPrototypeOf(object);
  6187. name = classObj.constructor["__bjsclassName__"];
  6188. }
  6189. if (!name) {
  6190. name = typeof object;
  6191. }
  6192. }
  6193. return name;
  6194. };
  6195. Tools.first = function (array, predicate) {
  6196. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6197. var el = array_1[_i];
  6198. if (predicate(el)) {
  6199. return el;
  6200. }
  6201. }
  6202. };
  6203. /**
  6204. * This method will return the name of the full name of the class, including its owning module (if any).
  6205. * 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).
  6206. * @param object the object to get the class name from
  6207. * @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.
  6208. */
  6209. Tools.getFullClassName = function (object, isType) {
  6210. if (isType === void 0) { isType = false; }
  6211. var className = null;
  6212. var moduleName = null;
  6213. if (!isType && object.getClassName) {
  6214. className = object.getClassName();
  6215. }
  6216. else {
  6217. if (object instanceof Object) {
  6218. var classObj = isType ? object : Object.getPrototypeOf(object);
  6219. className = classObj.constructor["__bjsclassName__"];
  6220. moduleName = classObj.constructor["__bjsmoduleName__"];
  6221. }
  6222. if (!className) {
  6223. className = typeof object;
  6224. }
  6225. }
  6226. if (!className) {
  6227. return null;
  6228. }
  6229. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6230. };
  6231. /**
  6232. * 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.
  6233. * @param array
  6234. */
  6235. Tools.arrayOrStringFeeder = function (array) {
  6236. return function (index) {
  6237. if (index >= array.length) {
  6238. return null;
  6239. }
  6240. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6241. if (val && val.getHashCode) {
  6242. val = val.getHashCode();
  6243. }
  6244. if (typeof val === "string") {
  6245. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6246. }
  6247. return val;
  6248. };
  6249. };
  6250. /**
  6251. * Compute the hashCode of a stream of number
  6252. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6253. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6254. * @return the hash code computed
  6255. */
  6256. Tools.hashCodeFromStream = function (feeder) {
  6257. // Based from here: http://stackoverflow.com/a/7616484/802124
  6258. var hash = 0;
  6259. var index = 0;
  6260. var chr = feeder(index++);
  6261. while (chr != null) {
  6262. hash = ((hash << 5) - hash) + chr;
  6263. hash |= 0; // Convert to 32bit integer
  6264. chr = feeder(index++);
  6265. }
  6266. return hash;
  6267. };
  6268. return Tools;
  6269. }());
  6270. Tools.BaseUrl = "";
  6271. Tools.CorsBehavior = "anonymous";
  6272. Tools.UseFallbackTexture = true;
  6273. // Used in case of a texture loading problem
  6274. 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";
  6275. // Logs
  6276. Tools._NoneLogLevel = 0;
  6277. Tools._MessageLogLevel = 1;
  6278. Tools._WarningLogLevel = 2;
  6279. Tools._ErrorLogLevel = 4;
  6280. Tools._LogCache = "";
  6281. Tools.errorsCount = 0;
  6282. Tools.Log = Tools._LogEnabled;
  6283. Tools.Warn = Tools._WarnEnabled;
  6284. Tools.Error = Tools._ErrorEnabled;
  6285. // Performances
  6286. Tools._PerformanceNoneLogLevel = 0;
  6287. Tools._PerformanceUserMarkLogLevel = 1;
  6288. Tools._PerformanceConsoleLogLevel = 2;
  6289. Tools._performance = window.performance;
  6290. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6291. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6292. BABYLON.Tools = Tools;
  6293. /**
  6294. * This class is used to track a performance counter which is number based.
  6295. * The user has access to many properties which give statistics of different nature
  6296. *
  6297. * The implementer can track two kinds of Performance Counter: time and count
  6298. * 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.
  6299. * 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.
  6300. */
  6301. var PerfCounter = (function () {
  6302. function PerfCounter() {
  6303. this._startMonitoringTime = 0;
  6304. this._min = 0;
  6305. this._max = 0;
  6306. this._average = 0;
  6307. this._lastSecAverage = 0;
  6308. this._current = 0;
  6309. this._totalValueCount = 0;
  6310. this._totalAccumulated = 0;
  6311. this._lastSecAccumulated = 0;
  6312. this._lastSecTime = 0;
  6313. this._lastSecValueCount = 0;
  6314. }
  6315. Object.defineProperty(PerfCounter.prototype, "min", {
  6316. /**
  6317. * Returns the smallest value ever
  6318. */
  6319. get: function () {
  6320. return this._min;
  6321. },
  6322. enumerable: true,
  6323. configurable: true
  6324. });
  6325. Object.defineProperty(PerfCounter.prototype, "max", {
  6326. /**
  6327. * Returns the biggest value ever
  6328. */
  6329. get: function () {
  6330. return this._max;
  6331. },
  6332. enumerable: true,
  6333. configurable: true
  6334. });
  6335. Object.defineProperty(PerfCounter.prototype, "average", {
  6336. /**
  6337. * Returns the average value since the performance counter is running
  6338. */
  6339. get: function () {
  6340. return this._average;
  6341. },
  6342. enumerable: true,
  6343. configurable: true
  6344. });
  6345. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6346. /**
  6347. * Returns the average value of the last second the counter was monitored
  6348. */
  6349. get: function () {
  6350. return this._lastSecAverage;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(PerfCounter.prototype, "current", {
  6356. /**
  6357. * Returns the current value
  6358. */
  6359. get: function () {
  6360. return this._current;
  6361. },
  6362. enumerable: true,
  6363. configurable: true
  6364. });
  6365. Object.defineProperty(PerfCounter.prototype, "total", {
  6366. get: function () {
  6367. return this._totalAccumulated;
  6368. },
  6369. enumerable: true,
  6370. configurable: true
  6371. });
  6372. /**
  6373. * Call this method to start monitoring a new frame.
  6374. * 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.
  6375. */
  6376. PerfCounter.prototype.fetchNewFrame = function () {
  6377. this._totalValueCount++;
  6378. this._current = 0;
  6379. this._lastSecValueCount++;
  6380. };
  6381. /**
  6382. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6383. * @param newCount the count value to add to the monitored count
  6384. * @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.
  6385. */
  6386. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6387. if (!PerfCounter.Enabled) {
  6388. return;
  6389. }
  6390. this._current += newCount;
  6391. if (fetchResult) {
  6392. this._fetchResult();
  6393. }
  6394. };
  6395. /**
  6396. * Start monitoring this performance counter
  6397. */
  6398. PerfCounter.prototype.beginMonitoring = function () {
  6399. if (!PerfCounter.Enabled) {
  6400. return;
  6401. }
  6402. this._startMonitoringTime = Tools.Now;
  6403. };
  6404. /**
  6405. * Compute the time lapsed since the previous beginMonitoring() call.
  6406. * @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
  6407. */
  6408. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6409. if (newFrame === void 0) { newFrame = true; }
  6410. if (!PerfCounter.Enabled) {
  6411. return;
  6412. }
  6413. if (newFrame) {
  6414. this.fetchNewFrame();
  6415. }
  6416. var currentTime = Tools.Now;
  6417. this._current = currentTime - this._startMonitoringTime;
  6418. if (newFrame) {
  6419. this._fetchResult();
  6420. }
  6421. };
  6422. PerfCounter.prototype._fetchResult = function () {
  6423. this._totalAccumulated += this._current;
  6424. this._lastSecAccumulated += this._current;
  6425. // Min/Max update
  6426. this._min = Math.min(this._min, this._current);
  6427. this._max = Math.max(this._max, this._current);
  6428. this._average = this._totalAccumulated / this._totalValueCount;
  6429. // Reset last sec?
  6430. var now = Tools.Now;
  6431. if ((now - this._lastSecTime) > 1000) {
  6432. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6433. this._lastSecTime = now;
  6434. this._lastSecAccumulated = 0;
  6435. this._lastSecValueCount = 0;
  6436. }
  6437. };
  6438. return PerfCounter;
  6439. }());
  6440. PerfCounter.Enabled = true;
  6441. BABYLON.PerfCounter = PerfCounter;
  6442. /**
  6443. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6444. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6445. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6446. * @param name The name of the class, case should be preserved
  6447. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6448. */
  6449. function className(name, module) {
  6450. return function (target) {
  6451. target["__bjsclassName__"] = name;
  6452. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6453. };
  6454. }
  6455. BABYLON.className = className;
  6456. /**
  6457. * An implementation of a loop for asynchronous functions.
  6458. */
  6459. var AsyncLoop = (function () {
  6460. /**
  6461. * Constroctor.
  6462. * @param iterations the number of iterations.
  6463. * @param _fn the function to run each iteration
  6464. * @param _successCallback the callback that will be called upon succesful execution
  6465. * @param offset starting offset.
  6466. */
  6467. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6468. if (offset === void 0) { offset = 0; }
  6469. this.iterations = iterations;
  6470. this._fn = _fn;
  6471. this._successCallback = _successCallback;
  6472. this.index = offset - 1;
  6473. this._done = false;
  6474. }
  6475. /**
  6476. * Execute the next iteration. Must be called after the last iteration was finished.
  6477. */
  6478. AsyncLoop.prototype.executeNext = function () {
  6479. if (!this._done) {
  6480. if (this.index + 1 < this.iterations) {
  6481. ++this.index;
  6482. this._fn(this);
  6483. }
  6484. else {
  6485. this.breakLoop();
  6486. }
  6487. }
  6488. };
  6489. /**
  6490. * Break the loop and run the success callback.
  6491. */
  6492. AsyncLoop.prototype.breakLoop = function () {
  6493. this._done = true;
  6494. this._successCallback();
  6495. };
  6496. /**
  6497. * Helper function
  6498. */
  6499. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6500. if (offset === void 0) { offset = 0; }
  6501. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6502. loop.executeNext();
  6503. return loop;
  6504. };
  6505. /**
  6506. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6507. * @param iterations total number of iterations
  6508. * @param syncedIterations number of synchronous iterations in each async iteration.
  6509. * @param fn the function to call each iteration.
  6510. * @param callback a success call back that will be called when iterating stops.
  6511. * @param breakFunction a break condition (optional)
  6512. * @param timeout timeout settings for the setTimeout function. default - 0.
  6513. * @constructor
  6514. */
  6515. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6516. if (timeout === void 0) { timeout = 0; }
  6517. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6518. if (breakFunction && breakFunction())
  6519. loop.breakLoop();
  6520. else {
  6521. setTimeout(function () {
  6522. for (var i = 0; i < syncedIterations; ++i) {
  6523. var iteration = (loop.index * syncedIterations) + i;
  6524. if (iteration >= iterations)
  6525. break;
  6526. fn(iteration);
  6527. if (breakFunction && breakFunction()) {
  6528. loop.breakLoop();
  6529. break;
  6530. }
  6531. }
  6532. loop.executeNext();
  6533. }, timeout);
  6534. }
  6535. }, callback);
  6536. };
  6537. return AsyncLoop;
  6538. }());
  6539. BABYLON.AsyncLoop = AsyncLoop;
  6540. })(BABYLON || (BABYLON = {}));
  6541. //# sourceMappingURL=babylon.tools.js.map
  6542. var BABYLON;
  6543. (function (BABYLON) {
  6544. var Internals;
  6545. (function (Internals) {
  6546. var _AlphaState = (function () {
  6547. /**
  6548. * Initializes the state.
  6549. */
  6550. function _AlphaState() {
  6551. this._isAlphaBlendDirty = false;
  6552. this._isBlendFunctionParametersDirty = false;
  6553. this._isBlendEquationParametersDirty = false;
  6554. this._isBlendConstantsDirty = false;
  6555. this._alphaBlend = false;
  6556. this._blendFunctionParameters = new Array(4);
  6557. this._blendEquationParameters = new Array(2);
  6558. this._blendConstants = new Array(4);
  6559. this.reset();
  6560. }
  6561. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6562. get: function () {
  6563. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6564. },
  6565. enumerable: true,
  6566. configurable: true
  6567. });
  6568. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6569. get: function () {
  6570. return this._alphaBlend;
  6571. },
  6572. set: function (value) {
  6573. if (this._alphaBlend === value) {
  6574. return;
  6575. }
  6576. this._alphaBlend = value;
  6577. this._isAlphaBlendDirty = true;
  6578. },
  6579. enumerable: true,
  6580. configurable: true
  6581. });
  6582. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6583. if (this._blendConstants[0] === r &&
  6584. this._blendConstants[1] === g &&
  6585. this._blendConstants[2] === b &&
  6586. this._blendConstants[3] === a) {
  6587. return;
  6588. }
  6589. this._blendConstants[0] = r;
  6590. this._blendConstants[1] = g;
  6591. this._blendConstants[2] = b;
  6592. this._blendConstants[3] = a;
  6593. this._isBlendConstantsDirty = true;
  6594. };
  6595. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6596. if (this._blendFunctionParameters[0] === value0 &&
  6597. this._blendFunctionParameters[1] === value1 &&
  6598. this._blendFunctionParameters[2] === value2 &&
  6599. this._blendFunctionParameters[3] === value3) {
  6600. return;
  6601. }
  6602. this._blendFunctionParameters[0] = value0;
  6603. this._blendFunctionParameters[1] = value1;
  6604. this._blendFunctionParameters[2] = value2;
  6605. this._blendFunctionParameters[3] = value3;
  6606. this._isBlendFunctionParametersDirty = true;
  6607. };
  6608. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6609. if (this._blendEquationParameters[0] === rgb &&
  6610. this._blendEquationParameters[1] === alpha) {
  6611. return;
  6612. }
  6613. this._blendEquationParameters[0] = rgb;
  6614. this._blendEquationParameters[1] = alpha;
  6615. this._isBlendEquationParametersDirty = true;
  6616. };
  6617. _AlphaState.prototype.reset = function () {
  6618. this._alphaBlend = false;
  6619. this._blendFunctionParameters[0] = null;
  6620. this._blendFunctionParameters[1] = null;
  6621. this._blendFunctionParameters[2] = null;
  6622. this._blendFunctionParameters[3] = null;
  6623. this._blendEquationParameters[0] = null;
  6624. this._blendEquationParameters[1] = null;
  6625. this._blendConstants[0] = null;
  6626. this._blendConstants[1] = null;
  6627. this._blendConstants[2] = null;
  6628. this._blendConstants[3] = null;
  6629. this._isAlphaBlendDirty = true;
  6630. this._isBlendFunctionParametersDirty = false;
  6631. this._isBlendEquationParametersDirty = false;
  6632. this._isBlendConstantsDirty = false;
  6633. };
  6634. _AlphaState.prototype.apply = function (gl) {
  6635. if (!this.isDirty) {
  6636. return;
  6637. }
  6638. // Alpha blend
  6639. if (this._isAlphaBlendDirty) {
  6640. if (this._alphaBlend) {
  6641. gl.enable(gl.BLEND);
  6642. }
  6643. else {
  6644. gl.disable(gl.BLEND);
  6645. }
  6646. this._isAlphaBlendDirty = false;
  6647. }
  6648. // Alpha function
  6649. if (this._isBlendFunctionParametersDirty) {
  6650. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6651. this._isBlendFunctionParametersDirty = false;
  6652. }
  6653. // Alpha equation
  6654. if (this._isBlendEquationParametersDirty) {
  6655. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6656. this._isBlendEquationParametersDirty = false;
  6657. }
  6658. // Constants
  6659. if (this._isBlendConstantsDirty) {
  6660. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6661. this._isBlendConstantsDirty = false;
  6662. }
  6663. };
  6664. return _AlphaState;
  6665. }());
  6666. Internals._AlphaState = _AlphaState;
  6667. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6668. })(BABYLON || (BABYLON = {}));
  6669. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6670. var BABYLON;
  6671. (function (BABYLON) {
  6672. var Internals;
  6673. (function (Internals) {
  6674. var _DepthCullingState = (function () {
  6675. /**
  6676. * Initializes the state.
  6677. */
  6678. function _DepthCullingState() {
  6679. this._isDepthTestDirty = false;
  6680. this._isDepthMaskDirty = false;
  6681. this._isDepthFuncDirty = false;
  6682. this._isCullFaceDirty = false;
  6683. this._isCullDirty = false;
  6684. this._isZOffsetDirty = false;
  6685. this.reset();
  6686. }
  6687. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6688. get: function () {
  6689. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6690. },
  6691. enumerable: true,
  6692. configurable: true
  6693. });
  6694. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6695. get: function () {
  6696. return this._zOffset;
  6697. },
  6698. set: function (value) {
  6699. if (this._zOffset === value) {
  6700. return;
  6701. }
  6702. this._zOffset = value;
  6703. this._isZOffsetDirty = true;
  6704. },
  6705. enumerable: true,
  6706. configurable: true
  6707. });
  6708. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6709. get: function () {
  6710. return this._cullFace;
  6711. },
  6712. set: function (value) {
  6713. if (this._cullFace === value) {
  6714. return;
  6715. }
  6716. this._cullFace = value;
  6717. this._isCullFaceDirty = true;
  6718. },
  6719. enumerable: true,
  6720. configurable: true
  6721. });
  6722. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6723. get: function () {
  6724. return this._cull;
  6725. },
  6726. set: function (value) {
  6727. if (this._cull === value) {
  6728. return;
  6729. }
  6730. this._cull = value;
  6731. this._isCullDirty = true;
  6732. },
  6733. enumerable: true,
  6734. configurable: true
  6735. });
  6736. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6737. get: function () {
  6738. return this._depthFunc;
  6739. },
  6740. set: function (value) {
  6741. if (this._depthFunc === value) {
  6742. return;
  6743. }
  6744. this._depthFunc = value;
  6745. this._isDepthFuncDirty = true;
  6746. },
  6747. enumerable: true,
  6748. configurable: true
  6749. });
  6750. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6751. get: function () {
  6752. return this._depthMask;
  6753. },
  6754. set: function (value) {
  6755. if (this._depthMask === value) {
  6756. return;
  6757. }
  6758. this._depthMask = value;
  6759. this._isDepthMaskDirty = true;
  6760. },
  6761. enumerable: true,
  6762. configurable: true
  6763. });
  6764. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6765. get: function () {
  6766. return this._depthTest;
  6767. },
  6768. set: function (value) {
  6769. if (this._depthTest === value) {
  6770. return;
  6771. }
  6772. this._depthTest = value;
  6773. this._isDepthTestDirty = true;
  6774. },
  6775. enumerable: true,
  6776. configurable: true
  6777. });
  6778. _DepthCullingState.prototype.reset = function () {
  6779. this._depthMask = true;
  6780. this._depthTest = true;
  6781. this._depthFunc = null;
  6782. this._cullFace = null;
  6783. this._cull = null;
  6784. this._zOffset = 0;
  6785. this._isDepthTestDirty = true;
  6786. this._isDepthMaskDirty = true;
  6787. this._isDepthFuncDirty = false;
  6788. this._isCullFaceDirty = false;
  6789. this._isCullDirty = false;
  6790. this._isZOffsetDirty = false;
  6791. };
  6792. _DepthCullingState.prototype.apply = function (gl) {
  6793. if (!this.isDirty) {
  6794. return;
  6795. }
  6796. // Cull
  6797. if (this._isCullDirty) {
  6798. if (this.cull) {
  6799. gl.enable(gl.CULL_FACE);
  6800. }
  6801. else {
  6802. gl.disable(gl.CULL_FACE);
  6803. }
  6804. this._isCullDirty = false;
  6805. }
  6806. // Cull face
  6807. if (this._isCullFaceDirty) {
  6808. gl.cullFace(this.cullFace);
  6809. this._isCullFaceDirty = false;
  6810. }
  6811. // Depth mask
  6812. if (this._isDepthMaskDirty) {
  6813. gl.depthMask(this.depthMask);
  6814. this._isDepthMaskDirty = false;
  6815. }
  6816. // Depth test
  6817. if (this._isDepthTestDirty) {
  6818. if (this.depthTest) {
  6819. gl.enable(gl.DEPTH_TEST);
  6820. }
  6821. else {
  6822. gl.disable(gl.DEPTH_TEST);
  6823. }
  6824. this._isDepthTestDirty = false;
  6825. }
  6826. // Depth func
  6827. if (this._isDepthFuncDirty) {
  6828. gl.depthFunc(this.depthFunc);
  6829. this._isDepthFuncDirty = false;
  6830. }
  6831. // zOffset
  6832. if (this._isZOffsetDirty) {
  6833. if (this.zOffset) {
  6834. gl.enable(gl.POLYGON_OFFSET_FILL);
  6835. gl.polygonOffset(this.zOffset, 0);
  6836. }
  6837. else {
  6838. gl.disable(gl.POLYGON_OFFSET_FILL);
  6839. }
  6840. this._isZOffsetDirty = false;
  6841. }
  6842. };
  6843. return _DepthCullingState;
  6844. }());
  6845. Internals._DepthCullingState = _DepthCullingState;
  6846. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6847. })(BABYLON || (BABYLON = {}));
  6848. //# sourceMappingURL=babylon.depthCullingState.js.map
  6849. var BABYLON;
  6850. (function (BABYLON) {
  6851. var Internals;
  6852. (function (Internals) {
  6853. var _StencilState = (function () {
  6854. function _StencilState() {
  6855. this._isStencilTestDirty = false;
  6856. this._isStencilMaskDirty = false;
  6857. this._isStencilFuncDirty = false;
  6858. this._isStencilOpDirty = false;
  6859. this.reset();
  6860. }
  6861. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6862. get: function () {
  6863. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6864. },
  6865. enumerable: true,
  6866. configurable: true
  6867. });
  6868. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6869. get: function () {
  6870. return this._stencilFunc;
  6871. },
  6872. set: function (value) {
  6873. if (this._stencilFunc === value) {
  6874. return;
  6875. }
  6876. this._stencilFunc = value;
  6877. this._isStencilFuncDirty = true;
  6878. },
  6879. enumerable: true,
  6880. configurable: true
  6881. });
  6882. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6883. get: function () {
  6884. return this._stencilFuncRef;
  6885. },
  6886. set: function (value) {
  6887. if (this._stencilFuncRef === value) {
  6888. return;
  6889. }
  6890. this._stencilFuncRef = value;
  6891. this._isStencilFuncDirty = true;
  6892. },
  6893. enumerable: true,
  6894. configurable: true
  6895. });
  6896. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6897. get: function () {
  6898. return this._stencilFuncMask;
  6899. },
  6900. set: function (value) {
  6901. if (this._stencilFuncMask === value) {
  6902. return;
  6903. }
  6904. this._stencilFuncMask = value;
  6905. this._isStencilFuncDirty = true;
  6906. },
  6907. enumerable: true,
  6908. configurable: true
  6909. });
  6910. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6911. get: function () {
  6912. return this._stencilOpStencilFail;
  6913. },
  6914. set: function (value) {
  6915. if (this._stencilOpStencilFail === value) {
  6916. return;
  6917. }
  6918. this._stencilOpStencilFail = value;
  6919. this._isStencilOpDirty = true;
  6920. },
  6921. enumerable: true,
  6922. configurable: true
  6923. });
  6924. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6925. get: function () {
  6926. return this._stencilOpDepthFail;
  6927. },
  6928. set: function (value) {
  6929. if (this._stencilOpDepthFail === value) {
  6930. return;
  6931. }
  6932. this._stencilOpDepthFail = value;
  6933. this._isStencilOpDirty = true;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6939. get: function () {
  6940. return this._stencilOpStencilDepthPass;
  6941. },
  6942. set: function (value) {
  6943. if (this._stencilOpStencilDepthPass === value) {
  6944. return;
  6945. }
  6946. this._stencilOpStencilDepthPass = value;
  6947. this._isStencilOpDirty = true;
  6948. },
  6949. enumerable: true,
  6950. configurable: true
  6951. });
  6952. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6953. get: function () {
  6954. return this._stencilMask;
  6955. },
  6956. set: function (value) {
  6957. if (this._stencilMask === value) {
  6958. return;
  6959. }
  6960. this._stencilMask = value;
  6961. this._isStencilMaskDirty = true;
  6962. },
  6963. enumerable: true,
  6964. configurable: true
  6965. });
  6966. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6967. get: function () {
  6968. return this._stencilTest;
  6969. },
  6970. set: function (value) {
  6971. if (this._stencilTest === value) {
  6972. return;
  6973. }
  6974. this._stencilTest = value;
  6975. this._isStencilTestDirty = true;
  6976. },
  6977. enumerable: true,
  6978. configurable: true
  6979. });
  6980. _StencilState.prototype.reset = function () {
  6981. this._stencilTest = false;
  6982. this._stencilMask = 0xFF;
  6983. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6984. this._stencilFuncRef = 1;
  6985. this._stencilFuncMask = 0xFF;
  6986. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6987. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6988. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6989. this._isStencilTestDirty = true;
  6990. this._isStencilMaskDirty = true;
  6991. this._isStencilFuncDirty = true;
  6992. this._isStencilOpDirty = true;
  6993. };
  6994. _StencilState.prototype.apply = function (gl) {
  6995. if (!this.isDirty) {
  6996. return;
  6997. }
  6998. // Stencil test
  6999. if (this._isStencilTestDirty) {
  7000. if (this.stencilTest) {
  7001. gl.enable(gl.STENCIL_TEST);
  7002. }
  7003. else {
  7004. gl.disable(gl.STENCIL_TEST);
  7005. }
  7006. this._isStencilTestDirty = false;
  7007. }
  7008. // Stencil mask
  7009. if (this._isStencilMaskDirty) {
  7010. gl.stencilMask(this.stencilMask);
  7011. this._isStencilMaskDirty = false;
  7012. }
  7013. // Stencil func
  7014. if (this._isStencilFuncDirty) {
  7015. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7016. this._isStencilFuncDirty = false;
  7017. }
  7018. // Stencil op
  7019. if (this._isStencilOpDirty) {
  7020. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7021. this._isStencilOpDirty = false;
  7022. }
  7023. };
  7024. return _StencilState;
  7025. }());
  7026. Internals._StencilState = _StencilState;
  7027. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7028. })(BABYLON || (BABYLON = {}));
  7029. //# sourceMappingURL=babylon.stencilState.js.map
  7030. var BABYLON;
  7031. (function (BABYLON) {
  7032. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7033. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7034. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7035. gl.compileShader(shader);
  7036. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7037. throw new Error(gl.getShaderInfoLog(shader));
  7038. }
  7039. return shader;
  7040. };
  7041. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7042. var magFilter = gl.NEAREST;
  7043. var minFilter = gl.NEAREST;
  7044. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7045. magFilter = gl.LINEAR;
  7046. if (generateMipMaps) {
  7047. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7048. }
  7049. else {
  7050. minFilter = gl.LINEAR;
  7051. }
  7052. }
  7053. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7054. magFilter = gl.LINEAR;
  7055. if (generateMipMaps) {
  7056. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7057. }
  7058. else {
  7059. minFilter = gl.LINEAR;
  7060. }
  7061. }
  7062. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7063. magFilter = gl.NEAREST;
  7064. if (generateMipMaps) {
  7065. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7066. }
  7067. else {
  7068. minFilter = gl.NEAREST;
  7069. }
  7070. }
  7071. return {
  7072. min: minFilter,
  7073. mag: magFilter
  7074. };
  7075. };
  7076. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7078. var engine = scene.getEngine();
  7079. if (!engine) {
  7080. return;
  7081. }
  7082. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7083. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7084. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7086. texture._baseWidth = width;
  7087. texture._baseHeight = height;
  7088. texture._width = potWidth;
  7089. texture._height = potHeight;
  7090. texture.isReady = true;
  7091. processFunction(potWidth, potHeight);
  7092. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7095. if (!noMipmap && !isCompressed) {
  7096. gl.generateMipmap(gl.TEXTURE_2D);
  7097. }
  7098. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7099. engine.resetTextureCache();
  7100. scene._removePendingData(texture);
  7101. texture.onLoadedCallbacks.forEach(function (callback) {
  7102. callback();
  7103. });
  7104. texture.onLoadedCallbacks = [];
  7105. };
  7106. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7107. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7108. var img;
  7109. var onload = function () {
  7110. loadedImages[index] = img;
  7111. loadedImages._internalCount++;
  7112. scene._removePendingData(img);
  7113. if (loadedImages._internalCount === 6) {
  7114. onfinish(loadedImages);
  7115. }
  7116. };
  7117. var onerror = function () {
  7118. scene._removePendingData(img);
  7119. if (onErrorCallBack) {
  7120. onErrorCallBack();
  7121. }
  7122. };
  7123. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7124. scene._addPendingData(img);
  7125. };
  7126. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7127. if (onError === void 0) { onError = null; }
  7128. var loadedImages = [];
  7129. loadedImages._internalCount = 0;
  7130. for (var index = 0; index < 6; index++) {
  7131. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7132. }
  7133. };
  7134. var InstancingAttributeInfo = (function () {
  7135. function InstancingAttributeInfo() {
  7136. }
  7137. return InstancingAttributeInfo;
  7138. }());
  7139. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7140. var EngineCapabilities = (function () {
  7141. function EngineCapabilities() {
  7142. }
  7143. return EngineCapabilities;
  7144. }());
  7145. BABYLON.EngineCapabilities = EngineCapabilities;
  7146. /**
  7147. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7148. */
  7149. var Engine = (function () {
  7150. /**
  7151. * @constructor
  7152. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7153. * @param {boolean} [antialias] - enable antialias
  7154. * @param options - further options to be sent to the getContext function
  7155. */
  7156. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7157. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7158. var _this = this;
  7159. // Public members
  7160. this.isFullscreen = false;
  7161. this.isPointerLock = false;
  7162. this.cullBackFaces = true;
  7163. this.renderEvenInBackground = true;
  7164. this.preventCacheWipeBetweenFrames = false;
  7165. // To enable/disable IDB support and avoid XHR on .manifest
  7166. this.enableOfflineSupport = BABYLON.Database;
  7167. this.scenes = new Array();
  7168. // Observables
  7169. /**
  7170. * Observable event triggered each time the rendering canvas is resized
  7171. */
  7172. this.onResizeObservable = new BABYLON.Observable();
  7173. /**
  7174. * Observable event triggered each time the canvas lost focus
  7175. */
  7176. this.onCanvasBlurObservable = new BABYLON.Observable();
  7177. this._windowIsBackground = false;
  7178. this._webGLVersion = 1.0;
  7179. this._badOS = false;
  7180. this._drawCalls = new BABYLON.PerfCounter();
  7181. this._renderingQueueLaunched = false;
  7182. this._activeRenderLoops = [];
  7183. // FPS
  7184. this.fpsRange = 60;
  7185. this.previousFramesDuration = [];
  7186. this.fps = 60;
  7187. this.deltaTime = 0;
  7188. // States
  7189. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7190. this._stencilState = new BABYLON.Internals._StencilState();
  7191. this._alphaState = new BABYLON.Internals._AlphaState();
  7192. this._alphaMode = Engine.ALPHA_DISABLE;
  7193. // Cache
  7194. this._loadedTexturesCache = new Array();
  7195. this._maxTextureChannels = 16;
  7196. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7197. this._compiledEffects = {};
  7198. this._vertexAttribArraysEnabled = [];
  7199. this._uintIndicesCurrentlySet = false;
  7200. this._currentBoundBuffer = new Array();
  7201. this._currentBufferPointers = [];
  7202. this._currentInstanceLocations = new Array();
  7203. this._currentInstanceBuffers = new Array();
  7204. this._vaoRecordInProgress = false;
  7205. this._mustWipeVertexAttributes = false;
  7206. // Hardware supported Compressed Textures
  7207. this._texturesSupported = new Array();
  7208. this._onVRFullScreenTriggered = function () {
  7209. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7210. //get the old size before we change
  7211. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7212. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7213. //get the width and height, change the render size
  7214. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7215. var width, height;
  7216. _this.setHardwareScalingLevel(1);
  7217. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7218. }
  7219. else {
  7220. //When the specs are implemented, need to uncomment this.
  7221. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7222. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7223. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7224. _this._vrDisplayEnabled = undefined;
  7225. }
  7226. };
  7227. this._renderingCanvas = canvas;
  7228. Engine.Instances.push(this);
  7229. options = options || {};
  7230. if (antialias != null) {
  7231. options.antialias = antialias;
  7232. }
  7233. if (options.preserveDrawingBuffer === undefined) {
  7234. options.preserveDrawingBuffer = false;
  7235. }
  7236. if (options.audioEngine === undefined) {
  7237. options.audioEngine = true;
  7238. }
  7239. if (options.stencil === undefined) {
  7240. options.stencil = true;
  7241. }
  7242. // GL
  7243. if (!options.disableWebGL2Support) {
  7244. try {
  7245. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7246. if (this._gl) {
  7247. this._webGLVersion = 2.0;
  7248. }
  7249. }
  7250. catch (e) {
  7251. // Do nothing
  7252. }
  7253. }
  7254. if (!this._gl) {
  7255. if (!canvas) {
  7256. throw new Error("The provided canvas is null or undefined.");
  7257. }
  7258. try {
  7259. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7260. }
  7261. catch (e) {
  7262. throw new Error("WebGL not supported");
  7263. }
  7264. }
  7265. if (!this._gl) {
  7266. throw new Error("WebGL not supported");
  7267. }
  7268. this._onBlur = function () {
  7269. _this._windowIsBackground = true;
  7270. };
  7271. this._onFocus = function () {
  7272. _this._windowIsBackground = false;
  7273. };
  7274. this._onCanvasBlur = function () {
  7275. _this.onCanvasBlurObservable.notifyObservers(_this);
  7276. };
  7277. window.addEventListener("blur", this._onBlur);
  7278. window.addEventListener("focus", this._onFocus);
  7279. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7280. // Viewport
  7281. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7282. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7283. this.resize();
  7284. // Caps
  7285. this._isStencilEnable = options.stencil;
  7286. this._caps = new EngineCapabilities();
  7287. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7288. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7289. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7290. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7291. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7292. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7293. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7294. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7295. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7296. // Infos
  7297. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7298. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7299. if (rendererInfo != null) {
  7300. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7301. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7302. }
  7303. if (!this._glVendor) {
  7304. this._glVendor = "Unknown vendor";
  7305. }
  7306. if (!this._glRenderer) {
  7307. this._glRenderer = "Unknown renderer";
  7308. }
  7309. // Extensions
  7310. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7311. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7312. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7313. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7314. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7315. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7316. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7317. 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');
  7318. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7319. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7320. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7321. this._caps.highPrecisionShaderSupported = true;
  7322. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7323. // Checks if some of the format renders first to allow the use of webgl inspector.
  7324. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7325. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7326. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7327. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7328. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7329. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7330. if (this._webGLVersion > 1) {
  7331. Engine.HALF_FLOAT_OES = 0x140B;
  7332. }
  7333. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7334. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7335. // Vertex array object
  7336. if (this._webGLVersion > 1) {
  7337. this._caps.vertexArrayObject = true;
  7338. }
  7339. else {
  7340. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7341. if (vertexArrayObjectExtension != null) {
  7342. this._caps.vertexArrayObject = true;
  7343. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7344. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7345. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7346. }
  7347. else {
  7348. this._caps.vertexArrayObject = false;
  7349. }
  7350. }
  7351. // Instances count
  7352. if (this._webGLVersion > 1) {
  7353. this._caps.instancedArrays = true;
  7354. }
  7355. else {
  7356. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7357. if (instanceExtension != null) {
  7358. this._caps.instancedArrays = true;
  7359. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7360. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7361. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7362. }
  7363. else {
  7364. this._caps.instancedArrays = false;
  7365. }
  7366. }
  7367. // Intelligently add supported compressed formats in order to check for.
  7368. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7369. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7370. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7371. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7372. if (this._caps.astc)
  7373. this.texturesSupported.push('-astc.ktx');
  7374. if (this._caps.s3tc)
  7375. this.texturesSupported.push('-dxt.ktx');
  7376. if (this._caps.pvrtc)
  7377. this.texturesSupported.push('-pvrtc.ktx');
  7378. if (this._caps.etc2)
  7379. this.texturesSupported.push('-etc2.ktx');
  7380. if (this._caps.etc1)
  7381. this.texturesSupported.push('-etc1.ktx');
  7382. if (this._gl.getShaderPrecisionFormat) {
  7383. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7384. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7385. }
  7386. // Depth buffer
  7387. this.setDepthBuffer(true);
  7388. this.setDepthFunctionToLessOrEqual();
  7389. this.setDepthWrite(true);
  7390. // Fullscreen
  7391. this._onFullscreenChange = function () {
  7392. if (document.fullscreen !== undefined) {
  7393. _this.isFullscreen = document.fullscreen;
  7394. }
  7395. else if (document.mozFullScreen !== undefined) {
  7396. _this.isFullscreen = document.mozFullScreen;
  7397. }
  7398. else if (document.webkitIsFullScreen !== undefined) {
  7399. _this.isFullscreen = document.webkitIsFullScreen;
  7400. }
  7401. else if (document.msIsFullScreen !== undefined) {
  7402. _this.isFullscreen = document.msIsFullScreen;
  7403. }
  7404. // Pointer lock
  7405. if (_this.isFullscreen && _this._pointerLockRequested) {
  7406. canvas.requestPointerLock = canvas.requestPointerLock ||
  7407. canvas.msRequestPointerLock ||
  7408. canvas.mozRequestPointerLock ||
  7409. canvas.webkitRequestPointerLock;
  7410. if (canvas.requestPointerLock) {
  7411. canvas.requestPointerLock();
  7412. }
  7413. }
  7414. };
  7415. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7416. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7417. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7418. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7419. // Pointer lock
  7420. this._onPointerLockChange = function () {
  7421. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7422. document.webkitPointerLockElement === canvas ||
  7423. document.msPointerLockElement === canvas ||
  7424. document.pointerLockElement === canvas);
  7425. };
  7426. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7427. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7428. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7429. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7430. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7431. Engine.audioEngine = new BABYLON.AudioEngine();
  7432. }
  7433. //Load WebVR Devices
  7434. if (options.autoEnableWebVR) {
  7435. this.initWebVR();
  7436. }
  7437. //Detect if we are running on a faulty buggy OS.
  7438. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7439. //ua sniffing is the tool of the devil.
  7440. this._badOS = regexp.test(navigator.userAgent);
  7441. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7442. }
  7443. Object.defineProperty(Engine, "LastCreatedEngine", {
  7444. get: function () {
  7445. if (Engine.Instances.length === 0) {
  7446. return null;
  7447. }
  7448. return Engine.Instances[Engine.Instances.length - 1];
  7449. },
  7450. enumerable: true,
  7451. configurable: true
  7452. });
  7453. Object.defineProperty(Engine, "LastCreatedScene", {
  7454. get: function () {
  7455. var lastCreatedEngine = Engine.LastCreatedEngine;
  7456. if (!lastCreatedEngine) {
  7457. return null;
  7458. }
  7459. if (lastCreatedEngine.scenes.length === 0) {
  7460. return null;
  7461. }
  7462. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7463. },
  7464. enumerable: true,
  7465. configurable: true
  7466. });
  7467. /**
  7468. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7469. */
  7470. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7471. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7472. var engine = Engine.Instances[engineIndex];
  7473. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7474. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7475. }
  7476. }
  7477. };
  7478. Object.defineProperty(Engine, "NEVER", {
  7479. get: function () {
  7480. return Engine._NEVER;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(Engine, "ALWAYS", {
  7486. get: function () {
  7487. return Engine._ALWAYS;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. Object.defineProperty(Engine, "LESS", {
  7493. get: function () {
  7494. return Engine._LESS;
  7495. },
  7496. enumerable: true,
  7497. configurable: true
  7498. });
  7499. Object.defineProperty(Engine, "EQUAL", {
  7500. get: function () {
  7501. return Engine._EQUAL;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(Engine, "LEQUAL", {
  7507. get: function () {
  7508. return Engine._LEQUAL;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. Object.defineProperty(Engine, "GREATER", {
  7514. get: function () {
  7515. return Engine._GREATER;
  7516. },
  7517. enumerable: true,
  7518. configurable: true
  7519. });
  7520. Object.defineProperty(Engine, "GEQUAL", {
  7521. get: function () {
  7522. return Engine._GEQUAL;
  7523. },
  7524. enumerable: true,
  7525. configurable: true
  7526. });
  7527. Object.defineProperty(Engine, "NOTEQUAL", {
  7528. get: function () {
  7529. return Engine._NOTEQUAL;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(Engine, "KEEP", {
  7535. get: function () {
  7536. return Engine._KEEP;
  7537. },
  7538. enumerable: true,
  7539. configurable: true
  7540. });
  7541. Object.defineProperty(Engine, "REPLACE", {
  7542. get: function () {
  7543. return Engine._REPLACE;
  7544. },
  7545. enumerable: true,
  7546. configurable: true
  7547. });
  7548. Object.defineProperty(Engine, "INCR", {
  7549. get: function () {
  7550. return Engine._INCR;
  7551. },
  7552. enumerable: true,
  7553. configurable: true
  7554. });
  7555. Object.defineProperty(Engine, "DECR", {
  7556. get: function () {
  7557. return Engine._DECR;
  7558. },
  7559. enumerable: true,
  7560. configurable: true
  7561. });
  7562. Object.defineProperty(Engine, "INVERT", {
  7563. get: function () {
  7564. return Engine._INVERT;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(Engine, "INCR_WRAP", {
  7570. get: function () {
  7571. return Engine._INCR_WRAP;
  7572. },
  7573. enumerable: true,
  7574. configurable: true
  7575. });
  7576. Object.defineProperty(Engine, "DECR_WRAP", {
  7577. get: function () {
  7578. return Engine._DECR_WRAP;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7584. get: function () {
  7585. return Engine._ALPHA_DISABLE;
  7586. },
  7587. enumerable: true,
  7588. configurable: true
  7589. });
  7590. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7591. get: function () {
  7592. return Engine._ALPHA_ONEONE;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. Object.defineProperty(Engine, "ALPHA_ADD", {
  7598. get: function () {
  7599. return Engine._ALPHA_ADD;
  7600. },
  7601. enumerable: true,
  7602. configurable: true
  7603. });
  7604. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7605. get: function () {
  7606. return Engine._ALPHA_COMBINE;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7612. get: function () {
  7613. return Engine._ALPHA_SUBTRACT;
  7614. },
  7615. enumerable: true,
  7616. configurable: true
  7617. });
  7618. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7619. get: function () {
  7620. return Engine._ALPHA_MULTIPLY;
  7621. },
  7622. enumerable: true,
  7623. configurable: true
  7624. });
  7625. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7626. get: function () {
  7627. return Engine._ALPHA_MAXIMIZED;
  7628. },
  7629. enumerable: true,
  7630. configurable: true
  7631. });
  7632. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7633. get: function () {
  7634. return Engine._ALPHA_PREMULTIPLIED;
  7635. },
  7636. enumerable: true,
  7637. configurable: true
  7638. });
  7639. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7640. get: function () {
  7641. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7642. },
  7643. enumerable: true,
  7644. configurable: true
  7645. });
  7646. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7647. get: function () {
  7648. return Engine._ALPHA_INTERPOLATE;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7654. get: function () {
  7655. return Engine._ALPHA_SCREENMODE;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7661. get: function () {
  7662. return Engine._DELAYLOADSTATE_NONE;
  7663. },
  7664. enumerable: true,
  7665. configurable: true
  7666. });
  7667. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7668. get: function () {
  7669. return Engine._DELAYLOADSTATE_LOADED;
  7670. },
  7671. enumerable: true,
  7672. configurable: true
  7673. });
  7674. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7675. get: function () {
  7676. return Engine._DELAYLOADSTATE_LOADING;
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7682. get: function () {
  7683. return Engine._DELAYLOADSTATE_NOTLOADED;
  7684. },
  7685. enumerable: true,
  7686. configurable: true
  7687. });
  7688. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7689. get: function () {
  7690. return Engine._TEXTUREFORMAT_ALPHA;
  7691. },
  7692. enumerable: true,
  7693. configurable: true
  7694. });
  7695. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7696. get: function () {
  7697. return Engine._TEXTUREFORMAT_LUMINANCE;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7703. get: function () {
  7704. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7705. },
  7706. enumerable: true,
  7707. configurable: true
  7708. });
  7709. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7710. get: function () {
  7711. return Engine._TEXTUREFORMAT_RGB;
  7712. },
  7713. enumerable: true,
  7714. configurable: true
  7715. });
  7716. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7717. get: function () {
  7718. return Engine._TEXTUREFORMAT_RGBA;
  7719. },
  7720. enumerable: true,
  7721. configurable: true
  7722. });
  7723. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7724. get: function () {
  7725. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7726. },
  7727. enumerable: true,
  7728. configurable: true
  7729. });
  7730. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7731. get: function () {
  7732. return Engine._TEXTURETYPE_FLOAT;
  7733. },
  7734. enumerable: true,
  7735. configurable: true
  7736. });
  7737. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7738. get: function () {
  7739. return Engine._TEXTURETYPE_HALF_FLOAT;
  7740. },
  7741. enumerable: true,
  7742. configurable: true
  7743. });
  7744. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7745. get: function () {
  7746. return Engine._SCALEMODE_FLOOR;
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7752. get: function () {
  7753. return Engine._SCALEMODE_NEAREST;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7759. get: function () {
  7760. return Engine._SCALEMODE_CEILING;
  7761. },
  7762. enumerable: true,
  7763. configurable: true
  7764. });
  7765. Object.defineProperty(Engine, "Version", {
  7766. get: function () {
  7767. return "3.0-beta";
  7768. },
  7769. enumerable: true,
  7770. configurable: true
  7771. });
  7772. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7773. get: function () {
  7774. return this._texturesSupported;
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7780. get: function () {
  7781. return this._textureFormatInUse;
  7782. },
  7783. enumerable: true,
  7784. configurable: true
  7785. });
  7786. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7787. // Empty texture
  7788. get: function () {
  7789. if (!this._emptyTexture) {
  7790. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7791. }
  7792. return this._emptyTexture;
  7793. },
  7794. enumerable: true,
  7795. configurable: true
  7796. });
  7797. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7798. get: function () {
  7799. if (!this._emptyCubeTexture) {
  7800. var faceData = new Uint8Array(4);
  7801. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7802. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7803. }
  7804. return this._emptyCubeTexture;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7810. get: function () {
  7811. return this._webGLVersion;
  7812. },
  7813. enumerable: true,
  7814. configurable: true
  7815. });
  7816. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7817. /**
  7818. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7819. */
  7820. get: function () {
  7821. return this._isStencilEnable;
  7822. },
  7823. enumerable: true,
  7824. configurable: true
  7825. });
  7826. Engine.prototype._prepareWorkingCanvas = function () {
  7827. if (this._workingCanvas) {
  7828. return;
  7829. }
  7830. this._workingCanvas = document.createElement("canvas");
  7831. this._workingContext = this._workingCanvas.getContext("2d");
  7832. };
  7833. Engine.prototype.resetTextureCache = function () {
  7834. for (var index = 0; index < this._maxTextureChannels; index++) {
  7835. this._activeTexturesCache[index] = null;
  7836. }
  7837. };
  7838. Engine.prototype.getGlInfo = function () {
  7839. return {
  7840. vendor: this._glVendor,
  7841. renderer: this._glRenderer,
  7842. version: this._glVersion
  7843. };
  7844. };
  7845. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7846. if (useScreen === void 0) { useScreen = false; }
  7847. var viewport = camera.viewport;
  7848. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7849. };
  7850. Engine.prototype.getRenderWidth = function (useScreen) {
  7851. if (useScreen === void 0) { useScreen = false; }
  7852. if (!useScreen && this._currentRenderTarget) {
  7853. return this._currentRenderTarget._width;
  7854. }
  7855. return this._renderingCanvas.width;
  7856. };
  7857. Engine.prototype.getRenderHeight = function (useScreen) {
  7858. if (useScreen === void 0) { useScreen = false; }
  7859. if (!useScreen && this._currentRenderTarget) {
  7860. return this._currentRenderTarget._height;
  7861. }
  7862. return this._renderingCanvas.height;
  7863. };
  7864. Engine.prototype.getRenderingCanvas = function () {
  7865. return this._renderingCanvas;
  7866. };
  7867. Engine.prototype.getRenderingCanvasClientRect = function () {
  7868. return this._renderingCanvas.getBoundingClientRect();
  7869. };
  7870. Engine.prototype.setHardwareScalingLevel = function (level) {
  7871. this._hardwareScalingLevel = level;
  7872. this.resize();
  7873. };
  7874. Engine.prototype.getHardwareScalingLevel = function () {
  7875. return this._hardwareScalingLevel;
  7876. };
  7877. Engine.prototype.getLoadedTexturesCache = function () {
  7878. return this._loadedTexturesCache;
  7879. };
  7880. Engine.prototype.getCaps = function () {
  7881. return this._caps;
  7882. };
  7883. Object.defineProperty(Engine.prototype, "drawCalls", {
  7884. get: function () {
  7885. return this._drawCalls.current;
  7886. },
  7887. enumerable: true,
  7888. configurable: true
  7889. });
  7890. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7891. get: function () {
  7892. return this._drawCalls;
  7893. },
  7894. enumerable: true,
  7895. configurable: true
  7896. });
  7897. Engine.prototype.getDepthFunction = function () {
  7898. return this._depthCullingState.depthFunc;
  7899. };
  7900. Engine.prototype.setDepthFunction = function (depthFunc) {
  7901. this._depthCullingState.depthFunc = depthFunc;
  7902. };
  7903. Engine.prototype.setDepthFunctionToGreater = function () {
  7904. this._depthCullingState.depthFunc = this._gl.GREATER;
  7905. };
  7906. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7907. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7908. };
  7909. Engine.prototype.setDepthFunctionToLess = function () {
  7910. this._depthCullingState.depthFunc = this._gl.LESS;
  7911. };
  7912. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7913. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7914. };
  7915. Engine.prototype.getStencilBuffer = function () {
  7916. return this._stencilState.stencilTest;
  7917. };
  7918. Engine.prototype.setStencilBuffer = function (enable) {
  7919. this._stencilState.stencilTest = enable;
  7920. };
  7921. Engine.prototype.getStencilMask = function () {
  7922. return this._stencilState.stencilMask;
  7923. };
  7924. Engine.prototype.setStencilMask = function (mask) {
  7925. this._stencilState.stencilMask = mask;
  7926. };
  7927. Engine.prototype.getStencilFunction = function () {
  7928. return this._stencilState.stencilFunc;
  7929. };
  7930. Engine.prototype.getStencilFunctionReference = function () {
  7931. return this._stencilState.stencilFuncRef;
  7932. };
  7933. Engine.prototype.getStencilFunctionMask = function () {
  7934. return this._stencilState.stencilFuncMask;
  7935. };
  7936. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7937. this._stencilState.stencilFunc = stencilFunc;
  7938. };
  7939. Engine.prototype.setStencilFunctionReference = function (reference) {
  7940. this._stencilState.stencilFuncRef = reference;
  7941. };
  7942. Engine.prototype.setStencilFunctionMask = function (mask) {
  7943. this._stencilState.stencilFuncMask = mask;
  7944. };
  7945. Engine.prototype.getStencilOperationFail = function () {
  7946. return this._stencilState.stencilOpStencilFail;
  7947. };
  7948. Engine.prototype.getStencilOperationDepthFail = function () {
  7949. return this._stencilState.stencilOpDepthFail;
  7950. };
  7951. Engine.prototype.getStencilOperationPass = function () {
  7952. return this._stencilState.stencilOpStencilDepthPass;
  7953. };
  7954. Engine.prototype.setStencilOperationFail = function (operation) {
  7955. this._stencilState.stencilOpStencilFail = operation;
  7956. };
  7957. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7958. this._stencilState.stencilOpDepthFail = operation;
  7959. };
  7960. Engine.prototype.setStencilOperationPass = function (operation) {
  7961. this._stencilState.stencilOpStencilDepthPass = operation;
  7962. };
  7963. Engine.prototype.setDitheringState = function (value) {
  7964. if (value) {
  7965. this._gl.enable(this._gl.DITHER);
  7966. }
  7967. else {
  7968. this._gl.disable(this._gl.DITHER);
  7969. }
  7970. };
  7971. /**
  7972. * stop executing a render loop function and remove it from the execution array
  7973. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7974. */
  7975. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7976. if (!renderFunction) {
  7977. this._activeRenderLoops = [];
  7978. return;
  7979. }
  7980. var index = this._activeRenderLoops.indexOf(renderFunction);
  7981. if (index >= 0) {
  7982. this._activeRenderLoops.splice(index, 1);
  7983. }
  7984. };
  7985. Engine.prototype._renderLoop = function () {
  7986. var shouldRender = true;
  7987. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7988. shouldRender = false;
  7989. }
  7990. if (shouldRender) {
  7991. // Start new frame
  7992. this.beginFrame();
  7993. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7994. var renderFunction = this._activeRenderLoops[index];
  7995. renderFunction();
  7996. }
  7997. // Present
  7998. this.endFrame();
  7999. }
  8000. if (this._activeRenderLoops.length > 0) {
  8001. // Register new frame
  8002. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8003. }
  8004. else {
  8005. this._renderingQueueLaunched = false;
  8006. }
  8007. };
  8008. /**
  8009. * Register and execute a render loop. The engine can have more than one render function.
  8010. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8011. * @example
  8012. * engine.runRenderLoop(function () {
  8013. * scene.render()
  8014. * })
  8015. */
  8016. Engine.prototype.runRenderLoop = function (renderFunction) {
  8017. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8018. return;
  8019. }
  8020. this._activeRenderLoops.push(renderFunction);
  8021. if (!this._renderingQueueLaunched) {
  8022. this._renderingQueueLaunched = true;
  8023. this._bindedRenderFunction = this._renderLoop.bind(this);
  8024. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8025. }
  8026. };
  8027. /**
  8028. * Toggle full screen mode.
  8029. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8030. * @param {any} options - an options object to be sent to the requestFullscreen function
  8031. */
  8032. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8033. if (this.isFullscreen) {
  8034. BABYLON.Tools.ExitFullscreen();
  8035. }
  8036. else {
  8037. this._pointerLockRequested = requestPointerLock;
  8038. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8039. }
  8040. };
  8041. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8042. if (stencil === void 0) { stencil = false; }
  8043. this.applyStates();
  8044. var mode = 0;
  8045. if (backBuffer && color) {
  8046. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8047. mode |= this._gl.COLOR_BUFFER_BIT;
  8048. }
  8049. if (depth) {
  8050. this._gl.clearDepth(1.0);
  8051. mode |= this._gl.DEPTH_BUFFER_BIT;
  8052. }
  8053. if (stencil) {
  8054. this._gl.clearStencil(0);
  8055. mode |= this._gl.STENCIL_BUFFER_BIT;
  8056. }
  8057. this._gl.clear(mode);
  8058. };
  8059. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8060. var gl = this._gl;
  8061. // Save state
  8062. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8063. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8064. // Change state
  8065. gl.enable(gl.SCISSOR_TEST);
  8066. gl.scissor(x, y, width, height);
  8067. // Clear
  8068. this.clear(clearColor, true, true, true);
  8069. // Restore state
  8070. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8071. if (curScissor === true) {
  8072. gl.enable(gl.SCISSOR_TEST);
  8073. }
  8074. else {
  8075. gl.disable(gl.SCISSOR_TEST);
  8076. }
  8077. };
  8078. /**
  8079. * Set the WebGL's viewport
  8080. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8081. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8082. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8083. */
  8084. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8085. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8086. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8087. var x = viewport.x || 0;
  8088. var y = viewport.y || 0;
  8089. this._cachedViewport = viewport;
  8090. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8091. };
  8092. /**
  8093. * Directly set the WebGL Viewport
  8094. * The x, y, width & height are directly passed to the WebGL call
  8095. * @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.
  8096. */
  8097. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8098. var currentViewport = this._cachedViewport;
  8099. this._cachedViewport = null;
  8100. this._gl.viewport(x, y, width, height);
  8101. return currentViewport;
  8102. };
  8103. Engine.prototype.beginFrame = function () {
  8104. this._measureFps();
  8105. };
  8106. Engine.prototype.endFrame = function () {
  8107. //force a flush in case we are using a bad OS.
  8108. if (this._badOS) {
  8109. this.flushFramebuffer();
  8110. }
  8111. //submit frame to the vr device, if enabled
  8112. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8113. this._vrDisplayEnabled.submitFrame();
  8114. }
  8115. };
  8116. /**
  8117. * resize the view according to the canvas' size.
  8118. * @example
  8119. * window.addEventListener("resize", function () {
  8120. * engine.resize();
  8121. * });
  8122. */
  8123. Engine.prototype.resize = function () {
  8124. // We're not resizing the size of the canvas while in VR mode & presenting
  8125. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8126. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8127. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8128. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8129. }
  8130. };
  8131. /**
  8132. * force a specific size of the canvas
  8133. * @param {number} width - the new canvas' width
  8134. * @param {number} height - the new canvas' height
  8135. */
  8136. Engine.prototype.setSize = function (width, height) {
  8137. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8138. return;
  8139. }
  8140. this._renderingCanvas.width = width;
  8141. this._renderingCanvas.height = height;
  8142. for (var index = 0; index < this.scenes.length; index++) {
  8143. var scene = this.scenes[index];
  8144. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8145. var cam = scene.cameras[camIndex];
  8146. cam._currentRenderId = 0;
  8147. }
  8148. }
  8149. if (this.onResizeObservable.hasObservers) {
  8150. this.onResizeObservable.notifyObservers(this);
  8151. }
  8152. };
  8153. //WebVR functions
  8154. Engine.prototype.isVRDevicePresent = function (callback) {
  8155. this.getVRDevice(null, function (device) {
  8156. callback(device !== null);
  8157. });
  8158. };
  8159. Engine.prototype.getVRDevice = function (name, callback) {
  8160. if (!this.vrDisplaysPromise) {
  8161. callback(null);
  8162. return;
  8163. }
  8164. this.vrDisplaysPromise.then(function (devices) {
  8165. if (devices.length > 0) {
  8166. if (name) {
  8167. var found = devices.some(function (device) {
  8168. if (device.displayName === name) {
  8169. callback(device);
  8170. return true;
  8171. }
  8172. else {
  8173. return false;
  8174. }
  8175. });
  8176. if (!found) {
  8177. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8178. callback(devices[0]);
  8179. }
  8180. }
  8181. else {
  8182. //choose the first one
  8183. callback(devices[0]);
  8184. }
  8185. }
  8186. else {
  8187. BABYLON.Tools.Error("No WebVR devices found!");
  8188. callback(null);
  8189. }
  8190. });
  8191. };
  8192. Engine.prototype.initWebVR = function () {
  8193. if (!this.vrDisplaysPromise) {
  8194. this._getVRDisplays();
  8195. }
  8196. };
  8197. Engine.prototype.enableVR = function (vrDevice) {
  8198. this._vrDisplayEnabled = vrDevice;
  8199. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8200. };
  8201. Engine.prototype.disableVR = function () {
  8202. if (this._vrDisplayEnabled) {
  8203. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8204. }
  8205. };
  8206. Engine.prototype._getVRDisplays = function () {
  8207. var _this = this;
  8208. var getWebVRDevices = function (devices) {
  8209. var size = devices.length;
  8210. var i = 0;
  8211. _this._vrDisplays = devices.filter(function (device) {
  8212. return devices[i] instanceof VRDisplay;
  8213. });
  8214. return _this._vrDisplays;
  8215. };
  8216. //using a key due to typescript
  8217. if (navigator.getVRDisplays) {
  8218. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8219. }
  8220. };
  8221. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8222. this._currentRenderTarget = texture;
  8223. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8224. var gl = this._gl;
  8225. if (texture.isCube) {
  8226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8227. }
  8228. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8229. this.wipeCaches();
  8230. };
  8231. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8232. if (this._currentFramebuffer !== framebuffer) {
  8233. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8234. this._currentFramebuffer = framebuffer;
  8235. }
  8236. };
  8237. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8238. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8239. this._currentRenderTarget = null;
  8240. // If MSAA, we need to bitblt back to main texture
  8241. var gl = this._gl;
  8242. if (texture._MSAAFramebuffer) {
  8243. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8244. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8245. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8246. }
  8247. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8248. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8249. gl.generateMipmap(gl.TEXTURE_2D);
  8250. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8251. }
  8252. if (onBeforeUnbind) {
  8253. if (texture._MSAAFramebuffer) {
  8254. // Bind the correct framebuffer
  8255. this.bindUnboundFramebuffer(texture._framebuffer);
  8256. }
  8257. onBeforeUnbind();
  8258. }
  8259. this.bindUnboundFramebuffer(null);
  8260. };
  8261. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8262. if (texture.generateMipMaps) {
  8263. var gl = this._gl;
  8264. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8265. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8266. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8267. }
  8268. };
  8269. Engine.prototype.flushFramebuffer = function () {
  8270. this._gl.flush();
  8271. };
  8272. Engine.prototype.restoreDefaultFramebuffer = function () {
  8273. this._currentRenderTarget = null;
  8274. this.bindUnboundFramebuffer(null);
  8275. this.setViewport(this._cachedViewport);
  8276. this.wipeCaches();
  8277. };
  8278. // UBOs
  8279. Engine.prototype.createUniformBuffer = function (elements) {
  8280. var ubo = this._gl.createBuffer();
  8281. this.bindUniformBuffer(ubo);
  8282. if (elements instanceof Float32Array) {
  8283. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8284. }
  8285. else {
  8286. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8287. }
  8288. this.bindUniformBuffer(null);
  8289. ubo.references = 1;
  8290. return ubo;
  8291. };
  8292. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8293. var ubo = this._gl.createBuffer();
  8294. this.bindUniformBuffer(ubo);
  8295. if (elements instanceof Float32Array) {
  8296. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8297. }
  8298. else {
  8299. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8300. }
  8301. this.bindUniformBuffer(null);
  8302. ubo.references = 1;
  8303. return ubo;
  8304. };
  8305. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8306. this.bindUniformBuffer(uniformBuffer);
  8307. if (offset === undefined) {
  8308. offset = 0;
  8309. }
  8310. if (count === undefined) {
  8311. if (elements instanceof Float32Array) {
  8312. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8313. }
  8314. else {
  8315. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8316. }
  8317. }
  8318. else {
  8319. if (elements instanceof Float32Array) {
  8320. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8321. }
  8322. else {
  8323. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8324. }
  8325. }
  8326. this.bindUniformBuffer(null);
  8327. };
  8328. // VBOs
  8329. Engine.prototype._resetVertexBufferBinding = function () {
  8330. this.bindArrayBuffer(null);
  8331. this._cachedVertexBuffers = null;
  8332. };
  8333. Engine.prototype.createVertexBuffer = function (vertices) {
  8334. var vbo = this._gl.createBuffer();
  8335. this.bindArrayBuffer(vbo);
  8336. if (vertices instanceof Float32Array) {
  8337. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8338. }
  8339. else {
  8340. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8341. }
  8342. this._resetVertexBufferBinding();
  8343. vbo.references = 1;
  8344. return vbo;
  8345. };
  8346. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8347. var vbo = this._gl.createBuffer();
  8348. this.bindArrayBuffer(vbo);
  8349. if (vertices instanceof Float32Array) {
  8350. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8351. }
  8352. else {
  8353. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8354. }
  8355. this._resetVertexBufferBinding();
  8356. vbo.references = 1;
  8357. return vbo;
  8358. };
  8359. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8360. this.bindArrayBuffer(vertexBuffer);
  8361. if (offset === undefined) {
  8362. offset = 0;
  8363. }
  8364. if (count === undefined) {
  8365. if (vertices instanceof Float32Array) {
  8366. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8367. }
  8368. else {
  8369. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8370. }
  8371. }
  8372. else {
  8373. if (vertices instanceof Float32Array) {
  8374. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8375. }
  8376. else {
  8377. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8378. }
  8379. }
  8380. this._resetVertexBufferBinding();
  8381. };
  8382. Engine.prototype._resetIndexBufferBinding = function () {
  8383. this.bindIndexBuffer(null);
  8384. this._cachedIndexBuffer = null;
  8385. };
  8386. Engine.prototype.createIndexBuffer = function (indices) {
  8387. var vbo = this._gl.createBuffer();
  8388. this.bindIndexBuffer(vbo);
  8389. // Check for 32 bits indices
  8390. var arrayBuffer;
  8391. var need32Bits = false;
  8392. if (indices instanceof Uint16Array) {
  8393. arrayBuffer = indices;
  8394. }
  8395. else {
  8396. //check 32 bit support
  8397. if (this._caps.uintIndices) {
  8398. if (indices instanceof Uint32Array) {
  8399. arrayBuffer = indices;
  8400. need32Bits = true;
  8401. }
  8402. else {
  8403. //number[] or Int32Array, check if 32 bit is necessary
  8404. for (var index = 0; index < indices.length; index++) {
  8405. if (indices[index] > 65535) {
  8406. need32Bits = true;
  8407. break;
  8408. }
  8409. }
  8410. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8411. }
  8412. }
  8413. else {
  8414. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8415. arrayBuffer = new Uint16Array(indices);
  8416. }
  8417. }
  8418. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8419. this._resetIndexBufferBinding();
  8420. vbo.references = 1;
  8421. vbo.is32Bits = need32Bits;
  8422. return vbo;
  8423. };
  8424. Engine.prototype.bindArrayBuffer = function (buffer) {
  8425. if (!this._vaoRecordInProgress) {
  8426. this._unBindVertexArrayObject();
  8427. }
  8428. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8429. };
  8430. Engine.prototype.bindUniformBuffer = function (buffer) {
  8431. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8432. };
  8433. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8434. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8435. };
  8436. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8437. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8438. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8439. };
  8440. ;
  8441. Engine.prototype.bindIndexBuffer = function (buffer) {
  8442. if (!this._vaoRecordInProgress) {
  8443. this._unBindVertexArrayObject();
  8444. }
  8445. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8446. };
  8447. Engine.prototype.bindBuffer = function (buffer, target) {
  8448. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8449. this._gl.bindBuffer(target, buffer);
  8450. this._currentBoundBuffer[target] = buffer;
  8451. }
  8452. };
  8453. Engine.prototype.updateArrayBuffer = function (data) {
  8454. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8455. };
  8456. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8457. var pointer = this._currentBufferPointers[indx];
  8458. var changed = false;
  8459. if (!pointer) {
  8460. changed = true;
  8461. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8462. }
  8463. else {
  8464. if (pointer.buffer !== buffer) {
  8465. pointer.buffer = buffer;
  8466. changed = true;
  8467. }
  8468. if (pointer.size !== size) {
  8469. pointer.size = size;
  8470. changed = true;
  8471. }
  8472. if (pointer.type !== type) {
  8473. pointer.type = type;
  8474. changed = true;
  8475. }
  8476. if (pointer.normalized !== normalized) {
  8477. pointer.normalized = normalized;
  8478. changed = true;
  8479. }
  8480. if (pointer.stride !== stride) {
  8481. pointer.stride = stride;
  8482. changed = true;
  8483. }
  8484. if (pointer.offset !== offset) {
  8485. pointer.offset = offset;
  8486. changed = true;
  8487. }
  8488. }
  8489. if (changed || this._vaoRecordInProgress) {
  8490. this.bindArrayBuffer(buffer);
  8491. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8492. }
  8493. };
  8494. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8495. if (indexBuffer == null) {
  8496. return;
  8497. }
  8498. if (this._cachedIndexBuffer !== indexBuffer) {
  8499. this._cachedIndexBuffer = indexBuffer;
  8500. this.bindIndexBuffer(indexBuffer);
  8501. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8502. }
  8503. };
  8504. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8505. var attributes = effect.getAttributesNames();
  8506. if (!this._vaoRecordInProgress) {
  8507. this._unBindVertexArrayObject();
  8508. }
  8509. this.unbindAllAttributes();
  8510. for (var index = 0; index < attributes.length; index++) {
  8511. var order = effect.getAttributeLocation(index);
  8512. if (order >= 0) {
  8513. var vertexBuffer = vertexBuffers[attributes[index]];
  8514. if (!vertexBuffer) {
  8515. continue;
  8516. }
  8517. this._gl.enableVertexAttribArray(order);
  8518. if (!this._vaoRecordInProgress) {
  8519. this._vertexAttribArraysEnabled[order] = true;
  8520. }
  8521. var buffer = vertexBuffer.getBuffer();
  8522. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8523. if (vertexBuffer.getIsInstanced()) {
  8524. this._gl.vertexAttribDivisor(order, 1);
  8525. if (!this._vaoRecordInProgress) {
  8526. this._currentInstanceLocations.push(order);
  8527. this._currentInstanceBuffers.push(buffer);
  8528. }
  8529. }
  8530. }
  8531. }
  8532. };
  8533. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8534. var vao = this._gl.createVertexArray();
  8535. this._vaoRecordInProgress = true;
  8536. this._gl.bindVertexArray(vao);
  8537. this._mustWipeVertexAttributes = true;
  8538. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8539. this.bindIndexBuffer(indexBuffer);
  8540. this._vaoRecordInProgress = false;
  8541. this._gl.bindVertexArray(null);
  8542. return vao;
  8543. };
  8544. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8545. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8546. this._cachedVertexArrayObject = vertexArrayObject;
  8547. this._gl.bindVertexArray(vertexArrayObject);
  8548. this._cachedVertexBuffers = null;
  8549. this._cachedIndexBuffer = null;
  8550. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8551. this._mustWipeVertexAttributes = true;
  8552. }
  8553. };
  8554. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8555. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8556. this._cachedVertexBuffers = vertexBuffer;
  8557. this._cachedEffectForVertexBuffers = effect;
  8558. var attributesCount = effect.getAttributesCount();
  8559. this._unBindVertexArrayObject();
  8560. this.unbindAllAttributes();
  8561. var offset = 0;
  8562. for (var index = 0; index < attributesCount; index++) {
  8563. if (index < vertexDeclaration.length) {
  8564. var order = effect.getAttributeLocation(index);
  8565. if (order >= 0) {
  8566. this._gl.enableVertexAttribArray(order);
  8567. this._vertexAttribArraysEnabled[order] = true;
  8568. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8569. }
  8570. offset += vertexDeclaration[index] * 4;
  8571. }
  8572. }
  8573. }
  8574. this._bindIndexBufferWithCache(indexBuffer);
  8575. };
  8576. Engine.prototype._unBindVertexArrayObject = function () {
  8577. if (!this._cachedVertexArrayObject) {
  8578. return;
  8579. }
  8580. this._cachedVertexArrayObject = null;
  8581. this._gl.bindVertexArray(null);
  8582. };
  8583. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8584. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8585. this._cachedVertexBuffers = vertexBuffers;
  8586. this._cachedEffectForVertexBuffers = effect;
  8587. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8588. }
  8589. this._bindIndexBufferWithCache(indexBuffer);
  8590. };
  8591. Engine.prototype.unbindInstanceAttributes = function () {
  8592. var boundBuffer;
  8593. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8594. var instancesBuffer = this._currentInstanceBuffers[i];
  8595. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8596. boundBuffer = instancesBuffer;
  8597. this.bindArrayBuffer(instancesBuffer);
  8598. }
  8599. var offsetLocation = this._currentInstanceLocations[i];
  8600. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8601. }
  8602. this._currentInstanceBuffers.length = 0;
  8603. this._currentInstanceLocations.length = 0;
  8604. };
  8605. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8606. this._gl.deleteVertexArray(vao);
  8607. };
  8608. Engine.prototype._releaseBuffer = function (buffer) {
  8609. buffer.references--;
  8610. if (buffer.references === 0) {
  8611. this._gl.deleteBuffer(buffer);
  8612. return true;
  8613. }
  8614. return false;
  8615. };
  8616. Engine.prototype.createInstancesBuffer = function (capacity) {
  8617. var buffer = this._gl.createBuffer();
  8618. buffer.capacity = capacity;
  8619. this.bindArrayBuffer(buffer);
  8620. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8621. return buffer;
  8622. };
  8623. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8624. this._gl.deleteBuffer(buffer);
  8625. };
  8626. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8627. this.bindArrayBuffer(instancesBuffer);
  8628. if (data) {
  8629. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8630. }
  8631. if (offsetLocations[0].index !== undefined) {
  8632. var stride = 0;
  8633. for (var i = 0; i < offsetLocations.length; i++) {
  8634. var ai = offsetLocations[i];
  8635. stride += ai.attributeSize * 4;
  8636. }
  8637. for (var i = 0; i < offsetLocations.length; i++) {
  8638. var ai = offsetLocations[i];
  8639. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8640. this._gl.enableVertexAttribArray(ai.index);
  8641. this._vertexAttribArraysEnabled[ai.index] = true;
  8642. }
  8643. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8644. this._gl.vertexAttribDivisor(ai.index, 1);
  8645. this._currentInstanceLocations.push(ai.index);
  8646. this._currentInstanceBuffers.push(instancesBuffer);
  8647. }
  8648. }
  8649. else {
  8650. for (var index = 0; index < 4; index++) {
  8651. var offsetLocation = offsetLocations[index];
  8652. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8653. this._gl.enableVertexAttribArray(offsetLocation);
  8654. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8655. }
  8656. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8657. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8658. this._currentInstanceLocations.push(offsetLocation);
  8659. this._currentInstanceBuffers.push(instancesBuffer);
  8660. }
  8661. }
  8662. };
  8663. Engine.prototype.applyStates = function () {
  8664. this._depthCullingState.apply(this._gl);
  8665. this._stencilState.apply(this._gl);
  8666. this._alphaState.apply(this._gl);
  8667. };
  8668. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8669. // Apply states
  8670. this.applyStates();
  8671. this._drawCalls.addCount(1, false);
  8672. // Render
  8673. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8674. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8675. if (instancesCount) {
  8676. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8677. return;
  8678. }
  8679. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8680. };
  8681. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8682. // Apply states
  8683. this.applyStates();
  8684. this._drawCalls.addCount(1, false);
  8685. if (instancesCount) {
  8686. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8687. return;
  8688. }
  8689. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8690. };
  8691. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8692. // Apply states
  8693. this.applyStates();
  8694. this._drawCalls.addCount(1, false);
  8695. if (instancesCount) {
  8696. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8697. return;
  8698. }
  8699. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8700. };
  8701. // Shaders
  8702. Engine.prototype._releaseEffect = function (effect) {
  8703. if (this._compiledEffects[effect._key]) {
  8704. delete this._compiledEffects[effect._key];
  8705. if (effect.getProgram()) {
  8706. this._gl.deleteProgram(effect.getProgram());
  8707. }
  8708. }
  8709. };
  8710. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8711. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8712. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8713. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8714. if (this._compiledEffects[name]) {
  8715. return this._compiledEffects[name];
  8716. }
  8717. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8718. effect._key = name;
  8719. this._compiledEffects[name] = effect;
  8720. return effect;
  8721. };
  8722. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8723. if (uniformsNames === void 0) { uniformsNames = []; }
  8724. if (samplers === void 0) { samplers = []; }
  8725. if (defines === void 0) { defines = ""; }
  8726. return this.createEffect({
  8727. vertex: "particles",
  8728. fragmentElement: fragmentName
  8729. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8730. };
  8731. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8732. context = context || this._gl;
  8733. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8734. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8735. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8736. var shaderProgram = context.createProgram();
  8737. context.attachShader(shaderProgram, vertexShader);
  8738. context.attachShader(shaderProgram, fragmentShader);
  8739. context.linkProgram(shaderProgram);
  8740. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8741. if (!linked) {
  8742. var error = context.getProgramInfoLog(shaderProgram);
  8743. if (error) {
  8744. throw new Error(error);
  8745. }
  8746. }
  8747. context.deleteShader(vertexShader);
  8748. context.deleteShader(fragmentShader);
  8749. return shaderProgram;
  8750. };
  8751. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8752. var results = [];
  8753. for (var index = 0; index < uniformsNames.length; index++) {
  8754. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8755. }
  8756. return results;
  8757. };
  8758. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8759. var results = [];
  8760. for (var index = 0; index < attributesNames.length; index++) {
  8761. try {
  8762. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8763. }
  8764. catch (e) {
  8765. results.push(-1);
  8766. }
  8767. }
  8768. return results;
  8769. };
  8770. Engine.prototype.enableEffect = function (effect) {
  8771. // Use program
  8772. this.setProgram(effect.getProgram());
  8773. this._currentEffect = effect;
  8774. if (effect.onBind) {
  8775. effect.onBind(effect);
  8776. }
  8777. };
  8778. Engine.prototype.setIntArray = function (uniform, array) {
  8779. if (!uniform)
  8780. return;
  8781. this._gl.uniform1iv(uniform, array);
  8782. };
  8783. Engine.prototype.setIntArray2 = function (uniform, array) {
  8784. if (!uniform || array.length % 2 !== 0)
  8785. return;
  8786. this._gl.uniform2iv(uniform, array);
  8787. };
  8788. Engine.prototype.setIntArray3 = function (uniform, array) {
  8789. if (!uniform || array.length % 3 !== 0)
  8790. return;
  8791. this._gl.uniform3iv(uniform, array);
  8792. };
  8793. Engine.prototype.setIntArray4 = function (uniform, array) {
  8794. if (!uniform || array.length % 4 !== 0)
  8795. return;
  8796. this._gl.uniform4iv(uniform, array);
  8797. };
  8798. Engine.prototype.setFloatArray = function (uniform, array) {
  8799. if (!uniform)
  8800. return;
  8801. this._gl.uniform1fv(uniform, array);
  8802. };
  8803. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8804. if (!uniform || array.length % 2 !== 0)
  8805. return;
  8806. this._gl.uniform2fv(uniform, array);
  8807. };
  8808. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8809. if (!uniform || array.length % 3 !== 0)
  8810. return;
  8811. this._gl.uniform3fv(uniform, array);
  8812. };
  8813. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8814. if (!uniform || array.length % 4 !== 0)
  8815. return;
  8816. this._gl.uniform4fv(uniform, array);
  8817. };
  8818. Engine.prototype.setArray = function (uniform, array) {
  8819. if (!uniform)
  8820. return;
  8821. this._gl.uniform1fv(uniform, array);
  8822. };
  8823. Engine.prototype.setArray2 = function (uniform, array) {
  8824. if (!uniform || array.length % 2 !== 0)
  8825. return;
  8826. this._gl.uniform2fv(uniform, array);
  8827. };
  8828. Engine.prototype.setArray3 = function (uniform, array) {
  8829. if (!uniform || array.length % 3 !== 0)
  8830. return;
  8831. this._gl.uniform3fv(uniform, array);
  8832. };
  8833. Engine.prototype.setArray4 = function (uniform, array) {
  8834. if (!uniform || array.length % 4 !== 0)
  8835. return;
  8836. this._gl.uniform4fv(uniform, array);
  8837. };
  8838. Engine.prototype.setMatrices = function (uniform, matrices) {
  8839. if (!uniform)
  8840. return;
  8841. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8842. };
  8843. Engine.prototype.setMatrix = function (uniform, matrix) {
  8844. if (!uniform)
  8845. return;
  8846. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8847. };
  8848. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8849. if (!uniform)
  8850. return;
  8851. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8852. };
  8853. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8854. if (!uniform)
  8855. return;
  8856. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8857. };
  8858. Engine.prototype.setFloat = function (uniform, value) {
  8859. if (!uniform)
  8860. return;
  8861. this._gl.uniform1f(uniform, value);
  8862. };
  8863. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8864. if (!uniform)
  8865. return;
  8866. this._gl.uniform2f(uniform, x, y);
  8867. };
  8868. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8869. if (!uniform)
  8870. return;
  8871. this._gl.uniform3f(uniform, x, y, z);
  8872. };
  8873. Engine.prototype.setBool = function (uniform, bool) {
  8874. if (!uniform)
  8875. return;
  8876. this._gl.uniform1i(uniform, bool);
  8877. };
  8878. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8879. if (!uniform)
  8880. return;
  8881. this._gl.uniform4f(uniform, x, y, z, w);
  8882. };
  8883. Engine.prototype.setColor3 = function (uniform, color3) {
  8884. if (!uniform)
  8885. return;
  8886. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8887. };
  8888. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8889. if (!uniform)
  8890. return;
  8891. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8892. };
  8893. // States
  8894. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8895. if (zOffset === void 0) { zOffset = 0; }
  8896. if (reverseSide === void 0) { reverseSide = false; }
  8897. // Culling
  8898. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8899. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8900. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8901. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8902. if (culling) {
  8903. this._depthCullingState.cullFace = cullFace;
  8904. this._depthCullingState.cull = true;
  8905. }
  8906. else {
  8907. this._depthCullingState.cull = false;
  8908. }
  8909. }
  8910. // Z offset
  8911. this.setZOffset(zOffset);
  8912. };
  8913. Engine.prototype.setZOffset = function (value) {
  8914. this._depthCullingState.zOffset = value;
  8915. };
  8916. Engine.prototype.getZOffset = function () {
  8917. return this._depthCullingState.zOffset;
  8918. };
  8919. Engine.prototype.setDepthBuffer = function (enable) {
  8920. this._depthCullingState.depthTest = enable;
  8921. };
  8922. Engine.prototype.getDepthWrite = function () {
  8923. return this._depthCullingState.depthMask;
  8924. };
  8925. Engine.prototype.setDepthWrite = function (enable) {
  8926. this._depthCullingState.depthMask = enable;
  8927. };
  8928. Engine.prototype.setColorWrite = function (enable) {
  8929. this._gl.colorMask(enable, enable, enable, enable);
  8930. };
  8931. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8932. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8933. };
  8934. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8935. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8936. if (this._alphaMode === mode) {
  8937. return;
  8938. }
  8939. switch (mode) {
  8940. case Engine.ALPHA_DISABLE:
  8941. this._alphaState.alphaBlend = false;
  8942. break;
  8943. case Engine.ALPHA_PREMULTIPLIED:
  8944. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8945. this._alphaState.alphaBlend = true;
  8946. break;
  8947. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8949. this._alphaState.alphaBlend = true;
  8950. break;
  8951. case Engine.ALPHA_COMBINE:
  8952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8953. this._alphaState.alphaBlend = true;
  8954. break;
  8955. case Engine.ALPHA_ONEONE:
  8956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8957. this._alphaState.alphaBlend = true;
  8958. break;
  8959. case Engine.ALPHA_ADD:
  8960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8961. this._alphaState.alphaBlend = true;
  8962. break;
  8963. case Engine.ALPHA_SUBTRACT:
  8964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8965. this._alphaState.alphaBlend = true;
  8966. break;
  8967. case Engine.ALPHA_MULTIPLY:
  8968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8969. this._alphaState.alphaBlend = true;
  8970. break;
  8971. case Engine.ALPHA_MAXIMIZED:
  8972. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8973. this._alphaState.alphaBlend = true;
  8974. break;
  8975. case Engine.ALPHA_INTERPOLATE:
  8976. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8977. this._alphaState.alphaBlend = true;
  8978. break;
  8979. case Engine.ALPHA_SCREENMODE:
  8980. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8981. this._alphaState.alphaBlend = true;
  8982. break;
  8983. }
  8984. if (!noDepthWriteChange) {
  8985. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8986. }
  8987. this._alphaMode = mode;
  8988. };
  8989. Engine.prototype.getAlphaMode = function () {
  8990. return this._alphaMode;
  8991. };
  8992. Engine.prototype.setAlphaTesting = function (enable) {
  8993. this._alphaTest = enable;
  8994. };
  8995. Engine.prototype.getAlphaTesting = function () {
  8996. return !!this._alphaTest;
  8997. };
  8998. // Textures
  8999. Engine.prototype.wipeCaches = function (bruteForce) {
  9000. if (this.preventCacheWipeBetweenFrames) {
  9001. return;
  9002. }
  9003. this.resetTextureCache();
  9004. this._currentEffect = null;
  9005. // 6/8/2017: deltakosh: Should not be required anymore.
  9006. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9007. if (bruteForce) {
  9008. this._stencilState.reset();
  9009. this._depthCullingState.reset();
  9010. this.setDepthFunctionToLessOrEqual();
  9011. this._alphaState.reset();
  9012. }
  9013. this._cachedVertexBuffers = null;
  9014. this._cachedIndexBuffer = null;
  9015. this._cachedEffectForVertexBuffers = null;
  9016. this._unBindVertexArrayObject();
  9017. this.bindIndexBuffer(null);
  9018. this.bindArrayBuffer(null);
  9019. };
  9020. /**
  9021. * Set the compressed texture format to use, based on the formats you have, and the formats
  9022. * supported by the hardware / browser.
  9023. *
  9024. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9025. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9026. * to API arguments needed to compressed textures. This puts the burden on the container
  9027. * generator to house the arcane code for determining these for current & future formats.
  9028. *
  9029. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9030. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9031. *
  9032. * Note: The result of this call is not taken into account when a texture is base64.
  9033. *
  9034. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9035. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9036. *
  9037. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9038. * @returns The extension selected.
  9039. */
  9040. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9041. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9042. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9043. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9044. return this._textureFormatInUse = this._texturesSupported[i];
  9045. }
  9046. }
  9047. }
  9048. // actively set format to nothing, to allow this to be called more than once
  9049. // and possibly fail the 2nd time
  9050. return this._textureFormatInUse = null;
  9051. };
  9052. /**
  9053. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9054. * @param {string} urlArg- This contains one of the following:
  9055. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9056. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9057. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9058. *
  9059. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9060. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9061. * @param {Scene} scene- Needed for loading to the correct scene.
  9062. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9063. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9064. * @param {callback} onError- Optional callback to be called upon failure.
  9065. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9066. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9067. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9068. *
  9069. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9070. */
  9071. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9072. var _this = this;
  9073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9074. if (onLoad === void 0) { onLoad = null; }
  9075. if (onError === void 0) { onError = null; }
  9076. if (buffer === void 0) { buffer = null; }
  9077. var texture = fallBack ? fallBack : this._gl.createTexture();
  9078. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9079. var fromData = url.substr(0, 5) === "data:";
  9080. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9081. // establish the file extension, if possible
  9082. var lastDot = url.lastIndexOf('.');
  9083. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9084. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9085. if (isDDS) {
  9086. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9087. }
  9088. var isTGA = (extension === ".tga");
  9089. // determine if a ktx file should be substituted
  9090. var isKTX = false;
  9091. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9092. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9093. isKTX = true;
  9094. }
  9095. scene._addPendingData(texture);
  9096. texture.url = url;
  9097. texture.noMipmap = noMipmap;
  9098. texture.references = 1;
  9099. texture.samplingMode = samplingMode;
  9100. texture.onLoadedCallbacks = [];
  9101. if (onLoad) {
  9102. texture.onLoadedCallbacks.push(onLoad);
  9103. }
  9104. if (!fallBack)
  9105. this._loadedTexturesCache.push(texture);
  9106. var onerror = function () {
  9107. scene._removePendingData(texture);
  9108. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9109. if (isKTX) {
  9110. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9111. }
  9112. else if (onError) {
  9113. onError();
  9114. }
  9115. };
  9116. var callback;
  9117. // processing for non-image formats
  9118. if (isKTX || isTGA || isDDS) {
  9119. if (isKTX) {
  9120. callback = function (data) {
  9121. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9122. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9123. ktx.uploadLevels(_this._gl, !noMipmap);
  9124. }, samplingMode);
  9125. };
  9126. }
  9127. else if (isTGA) {
  9128. callback = function (arrayBuffer) {
  9129. var data = new Uint8Array(arrayBuffer);
  9130. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9131. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9132. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9133. }, samplingMode);
  9134. };
  9135. }
  9136. else if (isDDS) {
  9137. callback = function (data) {
  9138. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9139. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9140. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9141. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9142. }, samplingMode);
  9143. };
  9144. }
  9145. if (!buffer) {
  9146. BABYLON.Tools.LoadFile(url, function (data) {
  9147. callback(data);
  9148. }, null, scene.database, true, onerror);
  9149. }
  9150. else {
  9151. callback(buffer);
  9152. }
  9153. // image format processing
  9154. }
  9155. else {
  9156. var onload = function (img) {
  9157. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9158. var isPot = (img.width === potWidth && img.height === potHeight);
  9159. if (!isPot) {
  9160. _this._prepareWorkingCanvas();
  9161. _this._workingCanvas.width = potWidth;
  9162. _this._workingCanvas.height = potHeight;
  9163. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9164. _this._workingContext.imageSmoothingEnabled = false;
  9165. _this._workingContext.mozImageSmoothingEnabled = false;
  9166. _this._workingContext.oImageSmoothingEnabled = false;
  9167. _this._workingContext.webkitImageSmoothingEnabled = false;
  9168. _this._workingContext.msImageSmoothingEnabled = false;
  9169. }
  9170. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9171. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9172. _this._workingContext.imageSmoothingEnabled = true;
  9173. _this._workingContext.mozImageSmoothingEnabled = true;
  9174. _this._workingContext.oImageSmoothingEnabled = true;
  9175. _this._workingContext.webkitImageSmoothingEnabled = true;
  9176. _this._workingContext.msImageSmoothingEnabled = true;
  9177. }
  9178. }
  9179. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9180. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9181. }, samplingMode);
  9182. };
  9183. if (!fromData || isBase64)
  9184. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9185. else if (buffer instanceof Array || typeof buffer === "string")
  9186. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9187. else
  9188. onload(buffer);
  9189. }
  9190. return texture;
  9191. };
  9192. Engine.prototype._getInternalFormat = function (format) {
  9193. var internalFormat = this._gl.RGBA;
  9194. switch (format) {
  9195. case Engine.TEXTUREFORMAT_ALPHA:
  9196. internalFormat = this._gl.ALPHA;
  9197. break;
  9198. case Engine.TEXTUREFORMAT_LUMINANCE:
  9199. internalFormat = this._gl.LUMINANCE;
  9200. break;
  9201. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9202. internalFormat = this._gl.LUMINANCE_ALPHA;
  9203. break;
  9204. case Engine.TEXTUREFORMAT_RGB:
  9205. internalFormat = this._gl.RGB;
  9206. break;
  9207. case Engine.TEXTUREFORMAT_RGBA:
  9208. internalFormat = this._gl.RGBA;
  9209. break;
  9210. }
  9211. return internalFormat;
  9212. };
  9213. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9214. if (compression === void 0) { compression = null; }
  9215. var internalFormat = this._getInternalFormat(format);
  9216. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9217. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9218. if (texture._width % 4 !== 0) {
  9219. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9220. }
  9221. if (compression) {
  9222. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9223. }
  9224. else {
  9225. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9226. }
  9227. if (texture.generateMipMaps) {
  9228. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9229. }
  9230. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9231. this.resetTextureCache();
  9232. texture.isReady = true;
  9233. };
  9234. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9235. if (compression === void 0) { compression = null; }
  9236. var texture = this._gl.createTexture();
  9237. texture._baseWidth = width;
  9238. texture._baseHeight = height;
  9239. texture._width = width;
  9240. texture._height = height;
  9241. texture.references = 1;
  9242. this.updateRawTexture(texture, data, format, invertY, compression);
  9243. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9244. // Filters
  9245. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9246. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9248. if (generateMipMaps) {
  9249. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9250. }
  9251. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9252. texture.samplingMode = samplingMode;
  9253. this._loadedTexturesCache.push(texture);
  9254. return texture;
  9255. };
  9256. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9257. var texture = this._gl.createTexture();
  9258. texture._baseWidth = width;
  9259. texture._baseHeight = height;
  9260. if (generateMipMaps) {
  9261. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9262. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9263. }
  9264. this.resetTextureCache();
  9265. texture._width = width;
  9266. texture._height = height;
  9267. texture.isReady = false;
  9268. texture.generateMipMaps = generateMipMaps;
  9269. texture.references = 1;
  9270. texture.samplingMode = samplingMode;
  9271. this.updateTextureSamplingMode(samplingMode, texture);
  9272. this._loadedTexturesCache.push(texture);
  9273. return texture;
  9274. };
  9275. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9276. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9277. if (texture.isCube) {
  9278. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9279. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9280. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9281. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9282. }
  9283. else {
  9284. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9285. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9287. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9288. }
  9289. texture.samplingMode = samplingMode;
  9290. };
  9291. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9292. if (premulAlpha === void 0) { premulAlpha = false; }
  9293. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9294. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9295. if (premulAlpha) {
  9296. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9297. }
  9298. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9299. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9300. if (texture.generateMipMaps) {
  9301. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9302. }
  9303. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9304. if (premulAlpha) {
  9305. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9306. }
  9307. this.resetTextureCache();
  9308. texture.isReady = true;
  9309. };
  9310. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9311. if (texture._isDisabled) {
  9312. return;
  9313. }
  9314. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9315. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9316. try {
  9317. // Testing video texture support
  9318. if (this._videoTextureSupported === undefined) {
  9319. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9320. if (this._gl.getError() !== 0) {
  9321. this._videoTextureSupported = false;
  9322. }
  9323. else {
  9324. this._videoTextureSupported = true;
  9325. }
  9326. }
  9327. // Copy video through the current working canvas if video texture is not supported
  9328. if (!this._videoTextureSupported) {
  9329. if (!texture._workingCanvas) {
  9330. texture._workingCanvas = document.createElement("canvas");
  9331. texture._workingContext = texture._workingCanvas.getContext("2d");
  9332. texture._workingCanvas.width = texture._width;
  9333. texture._workingCanvas.height = texture._height;
  9334. }
  9335. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9336. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9337. }
  9338. else {
  9339. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9340. }
  9341. if (texture.generateMipMaps) {
  9342. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9343. }
  9344. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9345. this.resetTextureCache();
  9346. texture.isReady = true;
  9347. }
  9348. catch (ex) {
  9349. // Something unexpected
  9350. // Let's disable the texture
  9351. texture._isDisabled = true;
  9352. }
  9353. };
  9354. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9355. // old version had a "generateMipMaps" arg instead of options.
  9356. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9357. // in the same way, generateDepthBuffer is defaulted to true
  9358. var generateMipMaps = false;
  9359. var generateDepthBuffer = true;
  9360. var generateStencilBuffer = false;
  9361. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9362. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9363. if (options !== undefined) {
  9364. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9365. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9366. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9367. type = options.type === undefined ? type : options.type;
  9368. if (options.samplingMode !== undefined) {
  9369. samplingMode = options.samplingMode;
  9370. }
  9371. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9372. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9373. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9374. }
  9375. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9376. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9377. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9378. }
  9379. }
  9380. var gl = this._gl;
  9381. var texture = gl.createTexture();
  9382. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9383. var width = size.width || size;
  9384. var height = size.height || size;
  9385. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9386. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9387. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9388. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9389. }
  9390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9394. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9395. // Create the framebuffer
  9396. var framebuffer = gl.createFramebuffer();
  9397. this.bindUnboundFramebuffer(framebuffer);
  9398. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9399. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9400. if (generateMipMaps) {
  9401. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9402. }
  9403. // Unbind
  9404. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9405. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9406. this.bindUnboundFramebuffer(null);
  9407. texture._framebuffer = framebuffer;
  9408. texture._baseWidth = width;
  9409. texture._baseHeight = height;
  9410. texture._width = width;
  9411. texture._height = height;
  9412. texture.isReady = true;
  9413. texture.samples = 1;
  9414. texture.generateMipMaps = generateMipMaps;
  9415. texture.references = 1;
  9416. texture.samplingMode = samplingMode;
  9417. texture.type = type;
  9418. texture._generateDepthBuffer = generateDepthBuffer;
  9419. texture._generateStencilBuffer = generateStencilBuffer;
  9420. this.resetTextureCache();
  9421. this._loadedTexturesCache.push(texture);
  9422. return texture;
  9423. };
  9424. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9425. var generateMipMaps = false;
  9426. var generateDepthBuffer = true;
  9427. var generateStencilBuffer = false;
  9428. var generateDepthTexture = false;
  9429. var textureCount = 1;
  9430. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9431. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9432. var types = [], samplingModes = [];
  9433. if (options !== undefined) {
  9434. generateMipMaps = options.generateMipMaps;
  9435. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9436. generateStencilBuffer = options.generateStencilBuffer;
  9437. generateDepthTexture = options.generateDepthTexture;
  9438. textureCount = options.textureCount || 1;
  9439. if (options.types) {
  9440. types = options.types;
  9441. }
  9442. if (options.samplingModes) {
  9443. samplingModes = options.samplingModes;
  9444. }
  9445. }
  9446. var gl = this._gl;
  9447. // Create the framebuffer
  9448. var framebuffer = gl.createFramebuffer();
  9449. this.bindUnboundFramebuffer(framebuffer);
  9450. var colorRenderbuffer = gl.createRenderbuffer();
  9451. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9452. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9453. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9454. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9456. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9457. var width = size.width || size;
  9458. var height = size.height || size;
  9459. var textures = [];
  9460. var attachments = [];
  9461. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9462. for (var i = 0; i < textureCount; i++) {
  9463. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9464. var type = types[i] || defaultType;
  9465. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9466. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9467. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9468. }
  9469. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9470. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9471. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9472. }
  9473. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9474. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9475. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9476. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9477. }
  9478. var texture = gl.createTexture();
  9479. var attachment = gl["COLOR_ATTACHMENT" + i];
  9480. textures.push(texture);
  9481. attachments.push(attachment);
  9482. gl.activeTexture(gl["TEXTURE" + i]);
  9483. gl.bindTexture(gl.TEXTURE_2D, texture);
  9484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9487. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9488. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9489. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9490. if (generateMipMaps) {
  9491. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9492. }
  9493. // Unbind
  9494. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9495. texture._framebuffer = framebuffer;
  9496. texture._depthStencilBuffer = depthStencilBuffer;
  9497. texture._baseWidth = width;
  9498. texture._baseHeight = height;
  9499. texture._width = width;
  9500. texture._height = height;
  9501. texture.isReady = true;
  9502. texture.samples = 1;
  9503. texture.generateMipMaps = generateMipMaps;
  9504. texture.references = 1;
  9505. texture.samplingMode = samplingMode;
  9506. texture.type = type;
  9507. texture._generateDepthBuffer = generateDepthBuffer;
  9508. texture._generateStencilBuffer = generateStencilBuffer;
  9509. this._loadedTexturesCache.push(texture);
  9510. }
  9511. if (generateDepthTexture) {
  9512. // Depth texture
  9513. var depthTexture = gl.createTexture();
  9514. gl.activeTexture(gl.TEXTURE0);
  9515. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9518. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9519. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9520. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9521. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9522. depthTexture._framebuffer = framebuffer;
  9523. depthTexture._baseWidth = width;
  9524. depthTexture._baseHeight = height;
  9525. depthTexture._width = width;
  9526. depthTexture._height = height;
  9527. depthTexture.isReady = true;
  9528. depthTexture.samples = 1;
  9529. depthTexture.generateMipMaps = generateMipMaps;
  9530. depthTexture.references = 1;
  9531. depthTexture.samplingMode = gl.NEAREST;
  9532. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9533. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9534. textures.push(depthTexture);
  9535. this._loadedTexturesCache.push(depthTexture);
  9536. }
  9537. gl.drawBuffers(attachments);
  9538. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9539. this.bindUnboundFramebuffer(null);
  9540. this.resetTextureCache();
  9541. return textures;
  9542. };
  9543. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9544. if (samples === void 0) { samples = 1; }
  9545. var depthStencilBuffer = null;
  9546. var gl = this._gl;
  9547. // Create the depth/stencil buffer
  9548. if (generateStencilBuffer) {
  9549. depthStencilBuffer = gl.createRenderbuffer();
  9550. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9551. if (samples > 1) {
  9552. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9553. }
  9554. else {
  9555. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9556. }
  9557. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9558. }
  9559. else if (generateDepthBuffer) {
  9560. depthStencilBuffer = gl.createRenderbuffer();
  9561. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9562. if (samples > 1) {
  9563. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9564. }
  9565. else {
  9566. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9567. }
  9568. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9569. }
  9570. return depthStencilBuffer;
  9571. };
  9572. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9573. if (this.webGLVersion < 2) {
  9574. return 1;
  9575. }
  9576. if (texture.samples === samples) {
  9577. return samples;
  9578. }
  9579. var gl = this._gl;
  9580. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9581. // Dispose previous render buffers
  9582. if (texture._depthStencilBuffer) {
  9583. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9584. }
  9585. if (texture._MSAAFramebuffer) {
  9586. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9587. }
  9588. if (texture._MSAARenderBuffer) {
  9589. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9590. }
  9591. if (samples > 1) {
  9592. texture._MSAAFramebuffer = gl.createFramebuffer();
  9593. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9594. var colorRenderbuffer = gl.createRenderbuffer();
  9595. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9596. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9597. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9598. texture._MSAARenderBuffer = colorRenderbuffer;
  9599. }
  9600. else {
  9601. this.bindUnboundFramebuffer(texture._framebuffer);
  9602. }
  9603. texture.samples = samples;
  9604. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9605. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9606. this.bindUnboundFramebuffer(null);
  9607. return samples;
  9608. };
  9609. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9610. var gl = this._gl;
  9611. var texture = gl.createTexture();
  9612. var generateMipMaps = true;
  9613. var generateDepthBuffer = true;
  9614. var generateStencilBuffer = false;
  9615. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9616. if (options !== undefined) {
  9617. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9618. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9619. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9620. if (options.samplingMode !== undefined) {
  9621. samplingMode = options.samplingMode;
  9622. }
  9623. }
  9624. texture.isCube = true;
  9625. texture.references = 1;
  9626. texture.generateMipMaps = generateMipMaps;
  9627. texture.references = 1;
  9628. texture.samples = 1;
  9629. texture.samplingMode = samplingMode;
  9630. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9631. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9632. for (var face = 0; face < 6; face++) {
  9633. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9634. }
  9635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9639. // Create the framebuffer
  9640. var framebuffer = gl.createFramebuffer();
  9641. this.bindUnboundFramebuffer(framebuffer);
  9642. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9643. // Mipmaps
  9644. if (texture.generateMipMaps) {
  9645. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9646. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9647. }
  9648. // Unbind
  9649. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9650. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9651. this.bindUnboundFramebuffer(null);
  9652. texture._framebuffer = framebuffer;
  9653. texture._width = size;
  9654. texture._height = size;
  9655. texture.isReady = true;
  9656. this.resetTextureCache();
  9657. this._loadedTexturesCache.push(texture);
  9658. return texture;
  9659. };
  9660. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9661. var _this = this;
  9662. if (onLoad === void 0) { onLoad = null; }
  9663. if (onError === void 0) { onError = null; }
  9664. var gl = this._gl;
  9665. var texture = gl.createTexture();
  9666. texture.isCube = true;
  9667. texture.url = rootUrl;
  9668. texture.references = 1;
  9669. texture.onLoadedCallbacks = [];
  9670. var isKTX = false;
  9671. var lastDot = rootUrl.lastIndexOf('.');
  9672. var extension = rootUrl.substring(lastDot).toLowerCase();
  9673. if (this._textureFormatInUse) {
  9674. extension = this._textureFormatInUse;
  9675. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9676. isKTX = true;
  9677. }
  9678. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9679. if (isDDS) {
  9680. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9681. }
  9682. if (isKTX) {
  9683. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9684. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9685. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9686. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9687. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9688. ktx.uploadLevels(_this._gl, !noMipmap);
  9689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9693. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9694. _this.resetTextureCache();
  9695. texture._width = ktx.pixelWidth;
  9696. texture._height = ktx.pixelHeight;
  9697. texture.isReady = true;
  9698. }, null, null, true, onError);
  9699. }
  9700. else if (isDDS) {
  9701. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9702. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9703. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9705. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9706. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9707. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9708. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9709. }
  9710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9714. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9715. _this.resetTextureCache();
  9716. texture._width = info.width;
  9717. texture._height = info.height;
  9718. texture.isReady = true;
  9719. }, null, null, true, onError);
  9720. }
  9721. else {
  9722. cascadeLoad(rootUrl, scene, function (imgs) {
  9723. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9724. var height = width;
  9725. _this._prepareWorkingCanvas();
  9726. _this._workingCanvas.width = width;
  9727. _this._workingCanvas.height = height;
  9728. var faces = [
  9729. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9730. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9731. ];
  9732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9733. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9734. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9735. for (var index = 0; index < faces.length; index++) {
  9736. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9737. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9738. }
  9739. if (!noMipmap) {
  9740. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9741. }
  9742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9745. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9746. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9747. _this.resetTextureCache();
  9748. texture._width = width;
  9749. texture._height = height;
  9750. texture.isReady = true;
  9751. texture.onLoadedCallbacks.forEach(function (callback) {
  9752. callback();
  9753. });
  9754. if (onLoad) {
  9755. onLoad();
  9756. }
  9757. }, files, onError);
  9758. }
  9759. this._loadedTexturesCache.push(texture);
  9760. return texture;
  9761. };
  9762. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9763. texture._width = width;
  9764. texture._height = height;
  9765. texture._size = width * height;
  9766. texture._baseWidth = width;
  9767. texture._baseHeight = height;
  9768. };
  9769. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9770. if (compression === void 0) { compression = null; }
  9771. if (level === void 0) { level = 0; }
  9772. var gl = this._gl;
  9773. var textureType = this._getWebGLTextureType(type);
  9774. var internalFormat = this._getInternalFormat(format);
  9775. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9776. var needConversion = false;
  9777. if (internalFormat === gl.RGB) {
  9778. internalFormat = gl.RGBA;
  9779. needConversion = true;
  9780. }
  9781. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9782. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9783. if (texture._width % 4 !== 0) {
  9784. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9785. }
  9786. var facesIndex = [
  9787. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9788. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9789. ];
  9790. // Data are known to be in +X +Y +Z -X -Y -Z
  9791. for (var index = 0; index < facesIndex.length; index++) {
  9792. var faceData = data[index];
  9793. if (compression) {
  9794. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9795. }
  9796. else {
  9797. if (needConversion) {
  9798. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9799. }
  9800. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9801. }
  9802. }
  9803. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9804. if (isPot && texture.generateMipMaps && level === 0) {
  9805. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9806. }
  9807. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9808. this.resetTextureCache();
  9809. texture.isReady = true;
  9810. };
  9811. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9812. if (compression === void 0) { compression = null; }
  9813. var gl = this._gl;
  9814. var texture = gl.createTexture();
  9815. texture.isCube = true;
  9816. texture.references = 1;
  9817. var textureType = this._getWebGLTextureType(type);
  9818. var internalFormat = this._getInternalFormat(format);
  9819. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9820. var needConversion = false;
  9821. if (internalFormat === gl.RGB) {
  9822. internalFormat = gl.RGBA;
  9823. needConversion = true;
  9824. }
  9825. var width = size;
  9826. var height = width;
  9827. texture._width = width;
  9828. texture._height = height;
  9829. // Double check on POT to generate Mips.
  9830. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9831. if (!isPot) {
  9832. generateMipMaps = false;
  9833. }
  9834. texture.generateMipMaps = generateMipMaps;
  9835. // Upload data if needed. The texture won t be ready until then.
  9836. if (data) {
  9837. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9838. }
  9839. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9840. // Filters
  9841. if (data && generateMipMaps) {
  9842. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9843. }
  9844. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9847. }
  9848. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9851. }
  9852. else {
  9853. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9856. }
  9857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9859. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9860. this._loadedTexturesCache.push(texture);
  9861. return texture;
  9862. };
  9863. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9864. var _this = this;
  9865. if (onLoad === void 0) { onLoad = null; }
  9866. if (onError === void 0) { onError = null; }
  9867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9868. if (invertY === void 0) { invertY = false; }
  9869. var gl = this._gl;
  9870. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9871. scene._addPendingData(texture);
  9872. texture.url = url;
  9873. var onerror = function () {
  9874. scene._removePendingData(texture);
  9875. if (onError) {
  9876. onError();
  9877. }
  9878. };
  9879. var internalCallback = function (data) {
  9880. var rgbeDataArrays = callback(data);
  9881. var facesIndex = [
  9882. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9883. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9884. ];
  9885. var width = texture._width;
  9886. var height = texture._height;
  9887. if (mipmmapGenerator) {
  9888. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9889. // I ll remove ASAP.
  9890. var textureType = _this._getWebGLTextureType(type);
  9891. var internalFormat = _this._getInternalFormat(format);
  9892. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9893. var needConversion = false;
  9894. if (internalFormat === gl.RGB) {
  9895. internalFormat = gl.RGBA;
  9896. needConversion = true;
  9897. }
  9898. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9899. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9900. var arrayTemp = [];
  9901. // Data are known to be in +X +Y +Z -X -Y -Z
  9902. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9903. arrayTemp.push(rgbeDataArrays[0]); // +X
  9904. arrayTemp.push(rgbeDataArrays[3]); // -X
  9905. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9906. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9907. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9908. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9909. var mipData = mipmmapGenerator(arrayTemp);
  9910. // mipData is order in +X -X +Y -Y +Z -Z
  9911. var mipFaces = [0, 2, 4, 1, 3, 5];
  9912. for (var level = 0; level < mipData.length; level++) {
  9913. var mipSize = width >> level;
  9914. for (var mipIndex in mipFaces) {
  9915. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9916. if (needConversion) {
  9917. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9918. }
  9919. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9920. }
  9921. }
  9922. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9923. }
  9924. else {
  9925. texture.generateMipMaps = !noMipmap;
  9926. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9927. }
  9928. texture.isReady = true;
  9929. _this.resetTextureCache();
  9930. scene._removePendingData(texture);
  9931. if (onLoad) {
  9932. onLoad();
  9933. }
  9934. };
  9935. BABYLON.Tools.LoadFile(url, function (data) {
  9936. internalCallback(data);
  9937. }, onerror, scene.database, true);
  9938. return texture;
  9939. };
  9940. ;
  9941. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9942. // Create new RGBA data container.
  9943. var rgbaData;
  9944. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9945. rgbaData = new Float32Array(width * height * 4);
  9946. }
  9947. else {
  9948. rgbaData = new Uint32Array(width * height * 4);
  9949. }
  9950. // Convert each pixel.
  9951. for (var x = 0; x < width; x++) {
  9952. for (var y = 0; y < height; y++) {
  9953. var index = (y * width + x) * 3;
  9954. var newIndex = (y * width + x) * 4;
  9955. // Map Old Value to new value.
  9956. rgbaData[newIndex + 0] = rgbData[index + 0];
  9957. rgbaData[newIndex + 1] = rgbData[index + 1];
  9958. rgbaData[newIndex + 2] = rgbData[index + 2];
  9959. // Add fully opaque alpha channel.
  9960. rgbaData[newIndex + 3] = 1;
  9961. }
  9962. }
  9963. return rgbaData;
  9964. };
  9965. Engine.prototype._releaseTexture = function (texture) {
  9966. var gl = this._gl;
  9967. if (texture._framebuffer) {
  9968. gl.deleteFramebuffer(texture._framebuffer);
  9969. }
  9970. if (texture._depthStencilBuffer) {
  9971. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9972. }
  9973. if (texture._MSAAFramebuffer) {
  9974. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9975. }
  9976. if (texture._MSAARenderBuffer) {
  9977. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9978. }
  9979. gl.deleteTexture(texture);
  9980. // Unbind channels
  9981. this.unbindAllTextures();
  9982. var index = this._loadedTexturesCache.indexOf(texture);
  9983. if (index !== -1) {
  9984. this._loadedTexturesCache.splice(index, 1);
  9985. }
  9986. };
  9987. Engine.prototype.setProgram = function (program) {
  9988. if (this._currentProgram !== program) {
  9989. this._gl.useProgram(program);
  9990. this._currentProgram = program;
  9991. }
  9992. };
  9993. Engine.prototype.bindSamplers = function (effect) {
  9994. this.setProgram(effect.getProgram());
  9995. var samplers = effect.getSamplers();
  9996. for (var index = 0; index < samplers.length; index++) {
  9997. var uniform = effect.getUniform(samplers[index]);
  9998. this._gl.uniform1i(uniform, index);
  9999. }
  10000. this._currentEffect = null;
  10001. };
  10002. Engine.prototype.activateTexture = function (texture) {
  10003. if (this._activeTexture !== texture) {
  10004. this._gl.activeTexture(texture);
  10005. this._activeTexture = texture;
  10006. }
  10007. };
  10008. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10009. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10010. this._gl.bindTexture(target, texture);
  10011. this._activeTexturesCache[this._activeTexture] = texture;
  10012. }
  10013. };
  10014. Engine.prototype._bindTexture = function (channel, texture) {
  10015. if (channel < 0) {
  10016. return;
  10017. }
  10018. this.activateTexture(this._gl.TEXTURE0 + channel);
  10019. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10020. };
  10021. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10022. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10023. };
  10024. Engine.prototype.unbindAllTextures = function () {
  10025. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10026. this.activateTexture(this._gl["TEXTURE" + channel]);
  10027. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10028. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10029. }
  10030. };
  10031. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10032. if (channel < 0) {
  10033. return;
  10034. }
  10035. this._gl.uniform1i(uniform, channel);
  10036. this._setTexture(channel, texture);
  10037. };
  10038. Engine.prototype._setTexture = function (channel, texture) {
  10039. // Not ready?
  10040. if (!texture) {
  10041. if (this._activeTexturesCache[channel] != null) {
  10042. this.activateTexture(this._gl["TEXTURE" + channel]);
  10043. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10044. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10045. }
  10046. return;
  10047. }
  10048. // Video
  10049. var alreadyActivated = false;
  10050. if (texture.video) {
  10051. this.activateTexture(this._gl["TEXTURE" + channel]);
  10052. alreadyActivated = true;
  10053. texture.update();
  10054. }
  10055. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10056. texture.delayLoad();
  10057. return;
  10058. }
  10059. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10060. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10061. if (this._activeTexturesCache[channel] === internalTexture) {
  10062. return;
  10063. }
  10064. if (!alreadyActivated) {
  10065. this.activateTexture(this._gl["TEXTURE" + channel]);
  10066. }
  10067. if (internalTexture.isCube) {
  10068. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10069. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10070. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10071. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10072. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10073. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10074. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10075. }
  10076. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10077. }
  10078. else {
  10079. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10080. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10081. internalTexture._cachedWrapU = texture.wrapU;
  10082. switch (texture.wrapU) {
  10083. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10084. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10085. break;
  10086. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10087. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10088. break;
  10089. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10090. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10091. break;
  10092. }
  10093. }
  10094. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10095. internalTexture._cachedWrapV = texture.wrapV;
  10096. switch (texture.wrapV) {
  10097. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10098. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10099. break;
  10100. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10101. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10102. break;
  10103. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10104. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10105. break;
  10106. }
  10107. }
  10108. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10109. }
  10110. };
  10111. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10112. if (channel < 0) {
  10113. return;
  10114. }
  10115. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10116. this._textureUnits = new Int32Array(textures.length);
  10117. }
  10118. for (var i = 0; i < textures.length; i++) {
  10119. this._textureUnits[i] = channel + i;
  10120. }
  10121. this._gl.uniform1iv(uniform, this._textureUnits);
  10122. for (var index = 0; index < textures.length; index++) {
  10123. this._setTexture(channel + index, textures[index]);
  10124. }
  10125. };
  10126. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10127. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10128. var value = texture.anisotropicFilteringLevel;
  10129. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10130. value = 1;
  10131. }
  10132. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10133. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10134. texture._cachedAnisotropicFilteringLevel = value;
  10135. }
  10136. };
  10137. Engine.prototype.readPixels = function (x, y, width, height) {
  10138. var data = new Uint8Array(height * width * 4);
  10139. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10140. return data;
  10141. };
  10142. /**
  10143. * Add an externaly attached data from its key.
  10144. * This method call will fail and return false, if such key already exists.
  10145. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10146. * @param key the unique key that identifies the data
  10147. * @param data the data object to associate to the key for this Engine instance
  10148. * @return true if no such key were already present and the data was added successfully, false otherwise
  10149. */
  10150. Engine.prototype.addExternalData = function (key, data) {
  10151. if (!this._externalData) {
  10152. this._externalData = new BABYLON.StringDictionary();
  10153. }
  10154. return this._externalData.add(key, data);
  10155. };
  10156. /**
  10157. * Get an externaly attached data from its key
  10158. * @param key the unique key that identifies the data
  10159. * @return the associated data, if present (can be null), or undefined if not present
  10160. */
  10161. Engine.prototype.getExternalData = function (key) {
  10162. if (!this._externalData) {
  10163. this._externalData = new BABYLON.StringDictionary();
  10164. }
  10165. return this._externalData.get(key);
  10166. };
  10167. /**
  10168. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10169. * @param key the unique key that identifies the data
  10170. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10171. * @return the associated data, can be null if the factory returned null.
  10172. */
  10173. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10174. if (!this._externalData) {
  10175. this._externalData = new BABYLON.StringDictionary();
  10176. }
  10177. return this._externalData.getOrAddWithFactory(key, factory);
  10178. };
  10179. /**
  10180. * Remove an externaly attached data from the Engine instance
  10181. * @param key the unique key that identifies the data
  10182. * @return true if the data was successfully removed, false if it doesn't exist
  10183. */
  10184. Engine.prototype.removeExternalData = function (key) {
  10185. if (!this._externalData) {
  10186. this._externalData = new BABYLON.StringDictionary();
  10187. }
  10188. return this._externalData.remove(key);
  10189. };
  10190. Engine.prototype.releaseInternalTexture = function (texture) {
  10191. if (!texture) {
  10192. return;
  10193. }
  10194. texture.references--;
  10195. // Final reference ?
  10196. if (texture.references === 0) {
  10197. var texturesCache = this.getLoadedTexturesCache();
  10198. var index = texturesCache.indexOf(texture);
  10199. if (index > -1) {
  10200. texturesCache.splice(index, 1);
  10201. }
  10202. this._releaseTexture(texture);
  10203. }
  10204. };
  10205. Engine.prototype.unbindAllAttributes = function () {
  10206. if (this._mustWipeVertexAttributes) {
  10207. this._mustWipeVertexAttributes = false;
  10208. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10209. this._gl.disableVertexAttribArray(i);
  10210. this._vertexAttribArraysEnabled[i] = false;
  10211. this._currentBufferPointers[i] = null;
  10212. }
  10213. return;
  10214. }
  10215. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10216. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10217. continue;
  10218. }
  10219. this._gl.disableVertexAttribArray(i);
  10220. this._vertexAttribArraysEnabled[i] = false;
  10221. this._currentBufferPointers[i] = null;
  10222. }
  10223. };
  10224. Engine.prototype.releaseEffects = function () {
  10225. for (var name in this._compiledEffects) {
  10226. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10227. }
  10228. this._compiledEffects = {};
  10229. };
  10230. // Dispose
  10231. Engine.prototype.dispose = function () {
  10232. this.hideLoadingUI();
  10233. this.stopRenderLoop();
  10234. // Empty texture
  10235. if (this._emptyTexture) {
  10236. this._releaseTexture(this._emptyTexture);
  10237. this._emptyTexture = null;
  10238. }
  10239. if (this._emptyCubeTexture) {
  10240. this._releaseTexture(this._emptyCubeTexture);
  10241. this._emptyCubeTexture = null;
  10242. }
  10243. // Release scenes
  10244. while (this.scenes.length) {
  10245. this.scenes[0].dispose();
  10246. }
  10247. // Release audio engine
  10248. if (Engine.audioEngine) {
  10249. Engine.audioEngine.dispose();
  10250. }
  10251. // Release effects
  10252. this.releaseEffects();
  10253. // Unbind
  10254. this.unbindAllAttributes();
  10255. this._gl = null;
  10256. //WebVR
  10257. this.disableVR();
  10258. // Events
  10259. window.removeEventListener("blur", this._onBlur);
  10260. window.removeEventListener("focus", this._onFocus);
  10261. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10262. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10263. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10264. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10265. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10266. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10267. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10268. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10269. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10270. // Remove from Instances
  10271. var index = Engine.Instances.indexOf(this);
  10272. if (index >= 0) {
  10273. Engine.Instances.splice(index, 1);
  10274. }
  10275. };
  10276. // Loading screen
  10277. Engine.prototype.displayLoadingUI = function () {
  10278. var loadingScreen = this.loadingScreen;
  10279. if (loadingScreen) {
  10280. loadingScreen.displayLoadingUI();
  10281. }
  10282. };
  10283. Engine.prototype.hideLoadingUI = function () {
  10284. var loadingScreen = this.loadingScreen;
  10285. if (loadingScreen) {
  10286. loadingScreen.hideLoadingUI();
  10287. }
  10288. };
  10289. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10290. get: function () {
  10291. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10292. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10293. return this._loadingScreen;
  10294. },
  10295. set: function (loadingScreen) {
  10296. this._loadingScreen = loadingScreen;
  10297. },
  10298. enumerable: true,
  10299. configurable: true
  10300. });
  10301. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10302. set: function (text) {
  10303. this.loadingScreen.loadingUIText = text;
  10304. },
  10305. enumerable: true,
  10306. configurable: true
  10307. });
  10308. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10309. set: function (color) {
  10310. this.loadingScreen.loadingUIBackgroundColor = color;
  10311. },
  10312. enumerable: true,
  10313. configurable: true
  10314. });
  10315. Engine.prototype.attachContextLostEvent = function (callback) {
  10316. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10317. };
  10318. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10319. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10320. };
  10321. Engine.prototype.getVertexShaderSource = function (program) {
  10322. var shaders = this._gl.getAttachedShaders(program);
  10323. return this._gl.getShaderSource(shaders[0]);
  10324. };
  10325. Engine.prototype.getFragmentShaderSource = function (program) {
  10326. var shaders = this._gl.getAttachedShaders(program);
  10327. return this._gl.getShaderSource(shaders[1]);
  10328. };
  10329. // FPS
  10330. Engine.prototype.getFps = function () {
  10331. return this.fps;
  10332. };
  10333. Engine.prototype.getDeltaTime = function () {
  10334. return this.deltaTime;
  10335. };
  10336. Engine.prototype._measureFps = function () {
  10337. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10338. var length = this.previousFramesDuration.length;
  10339. if (length >= 2) {
  10340. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10341. }
  10342. if (length >= this.fpsRange) {
  10343. if (length > this.fpsRange) {
  10344. this.previousFramesDuration.splice(0, 1);
  10345. length = this.previousFramesDuration.length;
  10346. }
  10347. var sum = 0;
  10348. for (var id = 0; id < length - 1; id++) {
  10349. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10350. }
  10351. this.fps = 1000.0 / (sum / (length - 1));
  10352. }
  10353. };
  10354. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10355. if (this._webGLVersion > 1) {
  10356. return this._caps.colorBufferFloat;
  10357. }
  10358. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10359. };
  10360. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10361. if (this._webGLVersion > 1) {
  10362. return this._caps.colorBufferFloat;
  10363. }
  10364. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10365. };
  10366. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10367. Engine.prototype._canRenderToFramebuffer = function (type) {
  10368. var gl = this._gl;
  10369. //clear existing errors
  10370. while (gl.getError() !== gl.NO_ERROR) { }
  10371. var successful = true;
  10372. var texture = gl.createTexture();
  10373. gl.bindTexture(gl.TEXTURE_2D, texture);
  10374. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10377. var fb = gl.createFramebuffer();
  10378. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10380. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10381. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10382. successful = successful && (gl.getError() === gl.NO_ERROR);
  10383. //try render by clearing frame buffer's color buffer
  10384. if (successful) {
  10385. gl.clear(gl.COLOR_BUFFER_BIT);
  10386. successful = successful && (gl.getError() === gl.NO_ERROR);
  10387. }
  10388. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10389. if (successful) {
  10390. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10391. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10392. var readFormat = gl.RGBA;
  10393. var readType = gl.UNSIGNED_BYTE;
  10394. var buffer = new Uint8Array(4);
  10395. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10396. successful = successful && (gl.getError() === gl.NO_ERROR);
  10397. }
  10398. //clean up
  10399. gl.deleteTexture(texture);
  10400. gl.deleteFramebuffer(fb);
  10401. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10402. //clear accumulated errors
  10403. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10404. return successful;
  10405. };
  10406. Engine.prototype._getWebGLTextureType = function (type) {
  10407. if (type === Engine.TEXTURETYPE_FLOAT) {
  10408. return this._gl.FLOAT;
  10409. }
  10410. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10411. // Add Half Float Constant.
  10412. return Engine.HALF_FLOAT_OES;
  10413. }
  10414. return this._gl.UNSIGNED_BYTE;
  10415. };
  10416. ;
  10417. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10418. if (this._webGLVersion === 1) {
  10419. return this._gl.RGBA;
  10420. }
  10421. if (type === Engine.TEXTURETYPE_FLOAT) {
  10422. return Engine.RGBA32F;
  10423. }
  10424. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10425. return Engine.RGBA16F;
  10426. }
  10427. return this._gl.RGBA;
  10428. };
  10429. ;
  10430. // Statics
  10431. Engine.isSupported = function () {
  10432. try {
  10433. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10434. if (navigator.isCocoonJS) {
  10435. return true;
  10436. }
  10437. var tempcanvas = document.createElement("canvas");
  10438. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10439. return gl != null && !!window.WebGLRenderingContext;
  10440. }
  10441. catch (e) {
  10442. return false;
  10443. }
  10444. };
  10445. return Engine;
  10446. }());
  10447. Engine.Instances = new Array();
  10448. // Const statics
  10449. Engine._ALPHA_DISABLE = 0;
  10450. Engine._ALPHA_ADD = 1;
  10451. Engine._ALPHA_COMBINE = 2;
  10452. Engine._ALPHA_SUBTRACT = 3;
  10453. Engine._ALPHA_MULTIPLY = 4;
  10454. Engine._ALPHA_MAXIMIZED = 5;
  10455. Engine._ALPHA_ONEONE = 6;
  10456. Engine._ALPHA_PREMULTIPLIED = 7;
  10457. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10458. Engine._ALPHA_INTERPOLATE = 9;
  10459. Engine._ALPHA_SCREENMODE = 10;
  10460. Engine._DELAYLOADSTATE_NONE = 0;
  10461. Engine._DELAYLOADSTATE_LOADED = 1;
  10462. Engine._DELAYLOADSTATE_LOADING = 2;
  10463. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10464. Engine._TEXTUREFORMAT_ALPHA = 0;
  10465. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10466. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10467. Engine._TEXTUREFORMAT_RGB = 4;
  10468. Engine._TEXTUREFORMAT_RGBA = 5;
  10469. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10470. Engine._TEXTURETYPE_FLOAT = 1;
  10471. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10472. // Depht or Stencil test Constants.
  10473. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10474. 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.
  10475. 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.
  10476. 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.
  10477. 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.
  10478. 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.
  10479. 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.
  10480. 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.
  10481. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10482. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10483. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10484. // Stencil Actions Constants.
  10485. Engine._KEEP = 0x1E00;
  10486. Engine._REPLACE = 0x1E01;
  10487. Engine._INCR = 0x1E02;
  10488. Engine._DECR = 0x1E03;
  10489. Engine._INVERT = 0x150A;
  10490. Engine._INCR_WRAP = 0x8507;
  10491. Engine._DECR_WRAP = 0x8508;
  10492. // Texture rescaling mode
  10493. Engine._SCALEMODE_FLOOR = 1;
  10494. Engine._SCALEMODE_NEAREST = 2;
  10495. Engine._SCALEMODE_CEILING = 3;
  10496. // Updatable statics so stick with vars here
  10497. Engine.CollisionsEpsilon = 0.001;
  10498. Engine.CodeRepository = "src/";
  10499. Engine.ShadersRepository = "src/Shaders/";
  10500. BABYLON.Engine = Engine;
  10501. })(BABYLON || (BABYLON = {}));
  10502. //# sourceMappingURL=babylon.engine.js.map
  10503. /// <reference path="Tools\babylon.decorators.ts" />
  10504. var BABYLON;
  10505. (function (BABYLON) {
  10506. /**
  10507. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10508. */
  10509. var Node = (function () {
  10510. /**
  10511. * @constructor
  10512. * @param {string} name - the name and id to be given to this node
  10513. * @param {BABYLON.Scene} the scene this node will be added to
  10514. */
  10515. function Node(name, scene) {
  10516. this.state = "";
  10517. this.metadata = null;
  10518. this.doNotSerialize = false;
  10519. this.animations = new Array();
  10520. this._ranges = {};
  10521. this._childrenFlag = -1;
  10522. this._isEnabled = true;
  10523. this._isReady = true;
  10524. this._currentRenderId = -1;
  10525. this._parentRenderId = -1;
  10526. /**
  10527. * An event triggered when the mesh is disposed.
  10528. * @type {BABYLON.Observable}
  10529. */
  10530. this.onDisposeObservable = new BABYLON.Observable();
  10531. this.name = name;
  10532. this.id = name;
  10533. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10534. this._initCache();
  10535. }
  10536. Object.defineProperty(Node.prototype, "parent", {
  10537. get: function () {
  10538. return this._parentNode;
  10539. },
  10540. set: function (parent) {
  10541. if (this._parentNode === parent) {
  10542. return;
  10543. }
  10544. if (this._parentNode) {
  10545. var index = this._parentNode._children.indexOf(this);
  10546. if (index !== -1) {
  10547. this._parentNode._children.splice(index, 1);
  10548. }
  10549. }
  10550. this._parentNode = parent;
  10551. if (this._parentNode) {
  10552. if (!this._parentNode._children) {
  10553. this._parentNode._children = new Array();
  10554. }
  10555. this._parentNode._children.push(this);
  10556. }
  10557. },
  10558. enumerable: true,
  10559. configurable: true
  10560. });
  10561. Node.prototype.getClassName = function () {
  10562. return "Node";
  10563. };
  10564. Object.defineProperty(Node.prototype, "onDispose", {
  10565. set: function (callback) {
  10566. if (this._onDisposeObserver) {
  10567. this.onDisposeObservable.remove(this._onDisposeObserver);
  10568. }
  10569. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10570. },
  10571. enumerable: true,
  10572. configurable: true
  10573. });
  10574. Node.prototype.getScene = function () {
  10575. return this._scene;
  10576. };
  10577. Node.prototype.getEngine = function () {
  10578. return this._scene.getEngine();
  10579. };
  10580. // override it in derived class
  10581. Node.prototype.getWorldMatrix = function () {
  10582. return BABYLON.Matrix.Identity();
  10583. };
  10584. // override it in derived class if you add new variables to the cache
  10585. // and call the parent class method
  10586. Node.prototype._initCache = function () {
  10587. this._cache = {};
  10588. this._cache.parent = undefined;
  10589. };
  10590. Node.prototype.updateCache = function (force) {
  10591. if (!force && this.isSynchronized())
  10592. return;
  10593. this._cache.parent = this.parent;
  10594. this._updateCache();
  10595. };
  10596. // override it in derived class if you add new variables to the cache
  10597. // and call the parent class method if !ignoreParentClass
  10598. Node.prototype._updateCache = function (ignoreParentClass) {
  10599. };
  10600. // override it in derived class if you add new variables to the cache
  10601. Node.prototype._isSynchronized = function () {
  10602. return true;
  10603. };
  10604. Node.prototype._markSyncedWithParent = function () {
  10605. this._parentRenderId = this.parent._currentRenderId;
  10606. };
  10607. Node.prototype.isSynchronizedWithParent = function () {
  10608. if (!this.parent) {
  10609. return true;
  10610. }
  10611. if (this._parentRenderId !== this.parent._currentRenderId) {
  10612. return false;
  10613. }
  10614. return this.parent.isSynchronized();
  10615. };
  10616. Node.prototype.isSynchronized = function (updateCache) {
  10617. var check = this.hasNewParent();
  10618. check = check || !this.isSynchronizedWithParent();
  10619. check = check || !this._isSynchronized();
  10620. if (updateCache)
  10621. this.updateCache(true);
  10622. return !check;
  10623. };
  10624. Node.prototype.hasNewParent = function (update) {
  10625. if (this._cache.parent === this.parent)
  10626. return false;
  10627. if (update)
  10628. this._cache.parent = this.parent;
  10629. return true;
  10630. };
  10631. /**
  10632. * Is this node ready to be used/rendered
  10633. * @return {boolean} is it ready
  10634. */
  10635. Node.prototype.isReady = function () {
  10636. return this._isReady;
  10637. };
  10638. /**
  10639. * Is this node enabled.
  10640. * If the node has a parent and is enabled, the parent will be inspected as well.
  10641. * @return {boolean} whether this node (and its parent) is enabled.
  10642. * @see setEnabled
  10643. */
  10644. Node.prototype.isEnabled = function () {
  10645. if (!this._isEnabled) {
  10646. return false;
  10647. }
  10648. if (this.parent) {
  10649. return this.parent.isEnabled();
  10650. }
  10651. return true;
  10652. };
  10653. /**
  10654. * Set the enabled state of this node.
  10655. * @param {boolean} value - the new enabled state
  10656. * @see isEnabled
  10657. */
  10658. Node.prototype.setEnabled = function (value) {
  10659. this._isEnabled = value;
  10660. };
  10661. /**
  10662. * Is this node a descendant of the given node.
  10663. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10664. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10665. * @see parent
  10666. */
  10667. Node.prototype.isDescendantOf = function (ancestor) {
  10668. if (this.parent) {
  10669. if (this.parent === ancestor) {
  10670. return true;
  10671. }
  10672. return this.parent.isDescendantOf(ancestor);
  10673. }
  10674. return false;
  10675. };
  10676. /**
  10677. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10678. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10679. * @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.
  10680. * @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.
  10681. */
  10682. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10683. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10684. if (!this._children) {
  10685. return;
  10686. }
  10687. for (var index = 0; index < this._children.length; index++) {
  10688. var item = this._children[index];
  10689. if (!predicate || predicate(item)) {
  10690. results.push(item);
  10691. }
  10692. if (!directDescendantsOnly) {
  10693. item._getDescendants(results, false, predicate);
  10694. }
  10695. }
  10696. };
  10697. /**
  10698. * Will return all nodes that have this node as ascendant.
  10699. * @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.
  10700. * @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.
  10701. * @return {BABYLON.Node[]} all children nodes of all types.
  10702. */
  10703. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10704. var results = [];
  10705. this._getDescendants(results, directDescendantsOnly, predicate);
  10706. return results;
  10707. };
  10708. /**
  10709. * Get all child-meshes of this node.
  10710. */
  10711. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10712. var results = [];
  10713. this._getDescendants(results, directDecendantsOnly, function (node) {
  10714. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10715. });
  10716. return results;
  10717. };
  10718. /**
  10719. * Get all direct children of this node.
  10720. */
  10721. Node.prototype.getChildren = function (predicate) {
  10722. return this.getDescendants(true, predicate);
  10723. };
  10724. Node.prototype._setReady = function (state) {
  10725. if (state === this._isReady) {
  10726. return;
  10727. }
  10728. if (!state) {
  10729. this._isReady = false;
  10730. return;
  10731. }
  10732. this._isReady = true;
  10733. if (this.onReady) {
  10734. this.onReady(this);
  10735. }
  10736. };
  10737. Node.prototype.getAnimationByName = function (name) {
  10738. for (var i = 0; i < this.animations.length; i++) {
  10739. var animation = this.animations[i];
  10740. if (animation.name === name) {
  10741. return animation;
  10742. }
  10743. }
  10744. return null;
  10745. };
  10746. Node.prototype.createAnimationRange = function (name, from, to) {
  10747. // check name not already in use
  10748. if (!this._ranges[name]) {
  10749. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10750. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10751. if (this.animations[i]) {
  10752. this.animations[i].createRange(name, from, to);
  10753. }
  10754. }
  10755. }
  10756. };
  10757. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10758. if (deleteFrames === void 0) { deleteFrames = true; }
  10759. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10760. if (this.animations[i]) {
  10761. this.animations[i].deleteRange(name, deleteFrames);
  10762. }
  10763. }
  10764. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10765. };
  10766. Node.prototype.getAnimationRange = function (name) {
  10767. return this._ranges[name];
  10768. };
  10769. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10770. var range = this.getAnimationRange(name);
  10771. if (!range) {
  10772. return null;
  10773. }
  10774. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10775. };
  10776. Node.prototype.serializeAnimationRanges = function () {
  10777. var serializationRanges = [];
  10778. for (var name in this._ranges) {
  10779. var range = {};
  10780. range.name = name;
  10781. range.from = this._ranges[name].from;
  10782. range.to = this._ranges[name].to;
  10783. serializationRanges.push(range);
  10784. }
  10785. return serializationRanges;
  10786. };
  10787. Node.prototype.dispose = function () {
  10788. this.parent = null;
  10789. // Callback
  10790. this.onDisposeObservable.notifyObservers(this);
  10791. this.onDisposeObservable.clear();
  10792. };
  10793. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10794. if (parsedNode.ranges) {
  10795. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10796. var data = parsedNode.ranges[index];
  10797. node.createAnimationRange(data.name, data.from, data.to);
  10798. }
  10799. }
  10800. };
  10801. return Node;
  10802. }());
  10803. __decorate([
  10804. BABYLON.serialize()
  10805. ], Node.prototype, "name", void 0);
  10806. __decorate([
  10807. BABYLON.serialize()
  10808. ], Node.prototype, "id", void 0);
  10809. __decorate([
  10810. BABYLON.serialize()
  10811. ], Node.prototype, "uniqueId", void 0);
  10812. __decorate([
  10813. BABYLON.serialize()
  10814. ], Node.prototype, "state", void 0);
  10815. __decorate([
  10816. BABYLON.serialize()
  10817. ], Node.prototype, "metadata", void 0);
  10818. BABYLON.Node = Node;
  10819. })(BABYLON || (BABYLON = {}));
  10820. //# sourceMappingURL=babylon.node.js.map
  10821. var BABYLON;
  10822. (function (BABYLON) {
  10823. var BoundingSphere = (function () {
  10824. function BoundingSphere(minimum, maximum) {
  10825. this.minimum = minimum;
  10826. this.maximum = maximum;
  10827. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10828. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10829. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10830. this.radius = distance * 0.5;
  10831. this.centerWorld = BABYLON.Vector3.Zero();
  10832. this._update(BABYLON.Matrix.Identity());
  10833. }
  10834. // Methods
  10835. BoundingSphere.prototype._update = function (world) {
  10836. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10837. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10838. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10839. };
  10840. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10841. for (var i = 0; i < 6; i++) {
  10842. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10843. return false;
  10844. }
  10845. return true;
  10846. };
  10847. BoundingSphere.prototype.intersectsPoint = function (point) {
  10848. var x = this.centerWorld.x - point.x;
  10849. var y = this.centerWorld.y - point.y;
  10850. var z = this.centerWorld.z - point.z;
  10851. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10852. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10853. return false;
  10854. return true;
  10855. };
  10856. // Statics
  10857. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10858. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10859. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10860. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10861. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10862. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10863. return false;
  10864. return true;
  10865. };
  10866. return BoundingSphere;
  10867. }());
  10868. BABYLON.BoundingSphere = BoundingSphere;
  10869. })(BABYLON || (BABYLON = {}));
  10870. //# sourceMappingURL=babylon.boundingSphere.js.map
  10871. var BABYLON;
  10872. (function (BABYLON) {
  10873. var BoundingBox = (function () {
  10874. function BoundingBox(minimum, maximum) {
  10875. this.minimum = minimum;
  10876. this.maximum = maximum;
  10877. this.vectors = new Array();
  10878. this.vectorsWorld = new Array();
  10879. // Bounding vectors
  10880. this.vectors.push(this.minimum.clone());
  10881. this.vectors.push(this.maximum.clone());
  10882. this.vectors.push(this.minimum.clone());
  10883. this.vectors[2].x = this.maximum.x;
  10884. this.vectors.push(this.minimum.clone());
  10885. this.vectors[3].y = this.maximum.y;
  10886. this.vectors.push(this.minimum.clone());
  10887. this.vectors[4].z = this.maximum.z;
  10888. this.vectors.push(this.maximum.clone());
  10889. this.vectors[5].z = this.minimum.z;
  10890. this.vectors.push(this.maximum.clone());
  10891. this.vectors[6].x = this.minimum.x;
  10892. this.vectors.push(this.maximum.clone());
  10893. this.vectors[7].y = this.minimum.y;
  10894. // OBB
  10895. this.center = this.maximum.add(this.minimum).scale(0.5);
  10896. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10897. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10898. // World
  10899. for (var index = 0; index < this.vectors.length; index++) {
  10900. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10901. }
  10902. this.minimumWorld = BABYLON.Vector3.Zero();
  10903. this.maximumWorld = BABYLON.Vector3.Zero();
  10904. this.centerWorld = BABYLON.Vector3.Zero();
  10905. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10906. this._update(BABYLON.Matrix.Identity());
  10907. }
  10908. // Methods
  10909. BoundingBox.prototype.getWorldMatrix = function () {
  10910. return this._worldMatrix;
  10911. };
  10912. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10913. this._worldMatrix.copyFrom(matrix);
  10914. return this;
  10915. };
  10916. BoundingBox.prototype._update = function (world) {
  10917. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10918. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10919. for (var index = 0; index < this.vectors.length; index++) {
  10920. var v = this.vectorsWorld[index];
  10921. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10922. if (v.x < this.minimumWorld.x)
  10923. this.minimumWorld.x = v.x;
  10924. if (v.y < this.minimumWorld.y)
  10925. this.minimumWorld.y = v.y;
  10926. if (v.z < this.minimumWorld.z)
  10927. this.minimumWorld.z = v.z;
  10928. if (v.x > this.maximumWorld.x)
  10929. this.maximumWorld.x = v.x;
  10930. if (v.y > this.maximumWorld.y)
  10931. this.maximumWorld.y = v.y;
  10932. if (v.z > this.maximumWorld.z)
  10933. this.maximumWorld.z = v.z;
  10934. }
  10935. // Extend
  10936. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10937. this.extendSizeWorld.scaleInPlace(0.5);
  10938. // OBB
  10939. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10940. this.centerWorld.scaleInPlace(0.5);
  10941. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10942. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10943. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10944. this._worldMatrix = world;
  10945. };
  10946. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10947. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10948. };
  10949. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10950. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10951. };
  10952. BoundingBox.prototype.intersectsPoint = function (point) {
  10953. var delta = -BABYLON.Epsilon;
  10954. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10955. return false;
  10956. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10957. return false;
  10958. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10959. return false;
  10960. return true;
  10961. };
  10962. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10963. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10964. };
  10965. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10966. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10967. return false;
  10968. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10969. return false;
  10970. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10971. return false;
  10972. return true;
  10973. };
  10974. // Statics
  10975. BoundingBox.Intersects = function (box0, box1) {
  10976. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10977. return false;
  10978. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10979. return false;
  10980. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10981. return false;
  10982. return true;
  10983. };
  10984. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10985. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10986. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10987. return (num <= (sphereRadius * sphereRadius));
  10988. };
  10989. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10990. for (var p = 0; p < 6; p++) {
  10991. for (var i = 0; i < 8; i++) {
  10992. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10993. return false;
  10994. }
  10995. }
  10996. }
  10997. return true;
  10998. };
  10999. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11000. for (var p = 0; p < 6; p++) {
  11001. var inCount = 8;
  11002. for (var i = 0; i < 8; i++) {
  11003. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11004. --inCount;
  11005. }
  11006. else {
  11007. break;
  11008. }
  11009. }
  11010. if (inCount === 0)
  11011. return false;
  11012. }
  11013. return true;
  11014. };
  11015. return BoundingBox;
  11016. }());
  11017. BABYLON.BoundingBox = BoundingBox;
  11018. })(BABYLON || (BABYLON = {}));
  11019. //# sourceMappingURL=babylon.boundingBox.js.map
  11020. var BABYLON;
  11021. (function (BABYLON) {
  11022. var computeBoxExtents = function (axis, box) {
  11023. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11024. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11025. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11026. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11027. var r = r0 + r1 + r2;
  11028. return {
  11029. min: p - r,
  11030. max: p + r
  11031. };
  11032. };
  11033. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11034. var axisOverlap = function (axis, box0, box1) {
  11035. var result0 = computeBoxExtents(axis, box0);
  11036. var result1 = computeBoxExtents(axis, box1);
  11037. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11038. };
  11039. var BoundingInfo = (function () {
  11040. function BoundingInfo(minimum, maximum) {
  11041. this.minimum = minimum;
  11042. this.maximum = maximum;
  11043. this._isLocked = false;
  11044. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11045. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11046. }
  11047. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11048. get: function () {
  11049. return this._isLocked;
  11050. },
  11051. set: function (value) {
  11052. this._isLocked = value;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. // Methods
  11058. BoundingInfo.prototype.update = function (world) {
  11059. if (this._isLocked) {
  11060. return;
  11061. }
  11062. this.boundingBox._update(world);
  11063. this.boundingSphere._update(world);
  11064. };
  11065. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11066. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11067. return false;
  11068. return this.boundingBox.isInFrustum(frustumPlanes);
  11069. };
  11070. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11071. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11072. };
  11073. BoundingInfo.prototype._checkCollision = function (collider) {
  11074. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11075. };
  11076. BoundingInfo.prototype.intersectsPoint = function (point) {
  11077. if (!this.boundingSphere.centerWorld) {
  11078. return false;
  11079. }
  11080. if (!this.boundingSphere.intersectsPoint(point)) {
  11081. return false;
  11082. }
  11083. if (!this.boundingBox.intersectsPoint(point)) {
  11084. return false;
  11085. }
  11086. return true;
  11087. };
  11088. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11089. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11090. return false;
  11091. }
  11092. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11093. return false;
  11094. }
  11095. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11096. return false;
  11097. }
  11098. if (!precise) {
  11099. return true;
  11100. }
  11101. var box0 = this.boundingBox;
  11102. var box1 = boundingInfo.boundingBox;
  11103. if (!axisOverlap(box0.directions[0], box0, box1))
  11104. return false;
  11105. if (!axisOverlap(box0.directions[1], box0, box1))
  11106. return false;
  11107. if (!axisOverlap(box0.directions[2], box0, box1))
  11108. return false;
  11109. if (!axisOverlap(box1.directions[0], box0, box1))
  11110. return false;
  11111. if (!axisOverlap(box1.directions[1], box0, box1))
  11112. return false;
  11113. if (!axisOverlap(box1.directions[2], box0, box1))
  11114. return false;
  11115. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11116. return false;
  11117. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11118. return false;
  11119. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11120. return false;
  11121. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11122. return false;
  11123. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11124. return false;
  11125. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11126. return false;
  11127. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11128. return false;
  11129. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11130. return false;
  11131. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11132. return false;
  11133. return true;
  11134. };
  11135. return BoundingInfo;
  11136. }());
  11137. BABYLON.BoundingInfo = BoundingInfo;
  11138. })(BABYLON || (BABYLON = {}));
  11139. //# sourceMappingURL=babylon.boundingInfo.js.map
  11140. var BABYLON;
  11141. (function (BABYLON) {
  11142. var AbstractMesh = (function (_super) {
  11143. __extends(AbstractMesh, _super);
  11144. // Constructor
  11145. function AbstractMesh(name, scene) {
  11146. var _this = _super.call(this, name, scene) || this;
  11147. _this._facetNb = 0; // facet number
  11148. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11149. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11150. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11151. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11152. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11153. _this._subDiv = {
  11154. max: 1,
  11155. X: 1,
  11156. Y: 1,
  11157. Z: 1
  11158. };
  11159. // Events
  11160. /**
  11161. * An event triggered when this mesh collides with another one
  11162. * @type {BABYLON.Observable}
  11163. */
  11164. _this.onCollideObservable = new BABYLON.Observable();
  11165. /**
  11166. * An event triggered when the collision's position changes
  11167. * @type {BABYLON.Observable}
  11168. */
  11169. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11170. /**
  11171. * An event triggered after the world matrix is updated
  11172. * @type {BABYLON.Observable}
  11173. */
  11174. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11175. // Properties
  11176. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11177. _this.position = BABYLON.Vector3.Zero();
  11178. _this._rotation = BABYLON.Vector3.Zero();
  11179. _this._scaling = BABYLON.Vector3.One();
  11180. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11181. _this.visibility = 1.0;
  11182. _this.alphaIndex = Number.MAX_VALUE;
  11183. _this.infiniteDistance = false;
  11184. _this.isVisible = true;
  11185. _this.isPickable = true;
  11186. _this.showBoundingBox = false;
  11187. _this.showSubMeshesBoundingBox = false;
  11188. _this.isBlocker = false;
  11189. _this.renderingGroupId = 0;
  11190. _this._receiveShadows = false;
  11191. _this.renderOutline = false;
  11192. _this.outlineColor = BABYLON.Color3.Red();
  11193. _this.outlineWidth = 0.02;
  11194. _this.renderOverlay = false;
  11195. _this.overlayColor = BABYLON.Color3.Red();
  11196. _this.overlayAlpha = 0.5;
  11197. _this._hasVertexAlpha = false;
  11198. _this._useVertexColors = true;
  11199. _this._computeBonesUsingShaders = true;
  11200. _this._numBoneInfluencers = 4;
  11201. _this._applyFog = true;
  11202. _this.scalingDeterminant = 1;
  11203. _this.useOctreeForRenderingSelection = true;
  11204. _this.useOctreeForPicking = true;
  11205. _this.useOctreeForCollisions = true;
  11206. _this.layerMask = 0x0FFFFFFF;
  11207. /**
  11208. * True if the mesh must be rendered in any case.
  11209. */
  11210. _this.alwaysSelectAsActiveMesh = false;
  11211. // Collisions
  11212. _this._checkCollisions = false;
  11213. _this._collisionMask = -1;
  11214. _this._collisionGroup = -1;
  11215. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11216. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11217. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11218. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11219. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11220. // Edges
  11221. _this.edgesWidth = 1;
  11222. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11223. // Cache
  11224. _this._localWorld = BABYLON.Matrix.Zero();
  11225. _this._worldMatrix = BABYLON.Matrix.Zero();
  11226. _this._absolutePosition = BABYLON.Vector3.Zero();
  11227. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11228. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11229. _this._isDirty = false;
  11230. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11231. _this._isDisposed = false;
  11232. _this._renderId = 0;
  11233. _this._intersectionsInProgress = new Array();
  11234. _this._isWorldMatrixFrozen = false;
  11235. _this._unIndexed = false;
  11236. _this._lightSources = new Array();
  11237. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11238. if (collidedMesh === void 0) { collidedMesh = null; }
  11239. //TODO move this to the collision coordinator!
  11240. if (_this.getScene().workerCollisions)
  11241. newPosition.multiplyInPlace(_this._collider.radius);
  11242. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11243. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11244. _this.position.addInPlace(_this._diffPositionForCollisions);
  11245. }
  11246. if (collidedMesh) {
  11247. _this.onCollideObservable.notifyObservers(collidedMesh);
  11248. }
  11249. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11250. };
  11251. _this.getScene().addMesh(_this);
  11252. _this._resyncLightSources();
  11253. return _this;
  11254. }
  11255. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11256. get: function () {
  11257. return AbstractMesh._BILLBOARDMODE_NONE;
  11258. },
  11259. enumerable: true,
  11260. configurable: true
  11261. });
  11262. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11263. get: function () {
  11264. return AbstractMesh._BILLBOARDMODE_X;
  11265. },
  11266. enumerable: true,
  11267. configurable: true
  11268. });
  11269. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11270. get: function () {
  11271. return AbstractMesh._BILLBOARDMODE_Y;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11277. get: function () {
  11278. return AbstractMesh._BILLBOARDMODE_Z;
  11279. },
  11280. enumerable: true,
  11281. configurable: true
  11282. });
  11283. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11284. get: function () {
  11285. return AbstractMesh._BILLBOARDMODE_ALL;
  11286. },
  11287. enumerable: true,
  11288. configurable: true
  11289. });
  11290. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11291. /**
  11292. * Read-only : the number of facets in the mesh
  11293. */
  11294. get: function () {
  11295. return this._facetNb;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11301. /**
  11302. * The number (integer) of subdivisions per axis in the partioning space
  11303. */
  11304. get: function () {
  11305. return this._partitioningSubdivisions;
  11306. },
  11307. set: function (nb) {
  11308. this._partitioningSubdivisions = nb;
  11309. },
  11310. enumerable: true,
  11311. configurable: true
  11312. });
  11313. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11314. /**
  11315. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11316. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11317. */
  11318. get: function () {
  11319. return this._partitioningBBoxRatio;
  11320. },
  11321. set: function (ratio) {
  11322. this._partitioningBBoxRatio = ratio;
  11323. },
  11324. enumerable: true,
  11325. configurable: true
  11326. });
  11327. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11328. /**
  11329. * Read-only boolean : is the feature facetData enabled ?
  11330. */
  11331. get: function () {
  11332. return this._facetDataEnabled;
  11333. },
  11334. enumerable: true,
  11335. configurable: true
  11336. });
  11337. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11338. set: function (callback) {
  11339. if (this._onCollideObserver) {
  11340. this.onCollideObservable.remove(this._onCollideObserver);
  11341. }
  11342. this._onCollideObserver = this.onCollideObservable.add(callback);
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11348. set: function (callback) {
  11349. if (this._onCollisionPositionChangeObserver) {
  11350. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11351. }
  11352. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11353. },
  11354. enumerable: true,
  11355. configurable: true
  11356. });
  11357. Object.defineProperty(AbstractMesh.prototype, "material", {
  11358. get: function () {
  11359. return this._material;
  11360. },
  11361. set: function (value) {
  11362. if (this._material === value) {
  11363. return;
  11364. }
  11365. this._material = value;
  11366. if (!this.subMeshes) {
  11367. return;
  11368. }
  11369. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11370. var subMesh = _a[_i];
  11371. subMesh.setEffect(null);
  11372. }
  11373. },
  11374. enumerable: true,
  11375. configurable: true
  11376. });
  11377. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11378. get: function () {
  11379. return this._receiveShadows;
  11380. },
  11381. set: function (value) {
  11382. if (this._receiveShadows === value) {
  11383. return;
  11384. }
  11385. this._receiveShadows = value;
  11386. this._markSubMeshesAsLightDirty();
  11387. },
  11388. enumerable: true,
  11389. configurable: true
  11390. });
  11391. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11392. get: function () {
  11393. return this._hasVertexAlpha;
  11394. },
  11395. set: function (value) {
  11396. if (this._hasVertexAlpha === value) {
  11397. return;
  11398. }
  11399. this._hasVertexAlpha = value;
  11400. this._markSubMeshesAsAttributesDirty();
  11401. },
  11402. enumerable: true,
  11403. configurable: true
  11404. });
  11405. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11406. get: function () {
  11407. return this._useVertexColors;
  11408. },
  11409. set: function (value) {
  11410. if (this._useVertexColors === value) {
  11411. return;
  11412. }
  11413. this._useVertexColors = value;
  11414. this._markSubMeshesAsAttributesDirty();
  11415. },
  11416. enumerable: true,
  11417. configurable: true
  11418. });
  11419. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11420. get: function () {
  11421. return this._computeBonesUsingShaders;
  11422. },
  11423. set: function (value) {
  11424. if (this._computeBonesUsingShaders === value) {
  11425. return;
  11426. }
  11427. this._computeBonesUsingShaders = value;
  11428. this._markSubMeshesAsAttributesDirty();
  11429. },
  11430. enumerable: true,
  11431. configurable: true
  11432. });
  11433. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11434. get: function () {
  11435. return this._numBoneInfluencers;
  11436. },
  11437. set: function (value) {
  11438. if (this._numBoneInfluencers === value) {
  11439. return;
  11440. }
  11441. this._numBoneInfluencers = value;
  11442. this._markSubMeshesAsAttributesDirty();
  11443. },
  11444. enumerable: true,
  11445. configurable: true
  11446. });
  11447. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11448. get: function () {
  11449. return this._applyFog;
  11450. },
  11451. set: function (value) {
  11452. if (this._applyFog === value) {
  11453. return;
  11454. }
  11455. this._applyFog = value;
  11456. this._markSubMeshesAsMiscDirty();
  11457. },
  11458. enumerable: true,
  11459. configurable: true
  11460. });
  11461. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11462. get: function () {
  11463. return this._collisionMask;
  11464. },
  11465. set: function (mask) {
  11466. this._collisionMask = !isNaN(mask) ? mask : -1;
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11472. get: function () {
  11473. return this._collisionGroup;
  11474. },
  11475. set: function (mask) {
  11476. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11482. get: function () {
  11483. return null;
  11484. },
  11485. enumerable: true,
  11486. configurable: true
  11487. });
  11488. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11489. get: function () {
  11490. return this._skeleton;
  11491. },
  11492. set: function (value) {
  11493. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11494. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11495. }
  11496. if (value && value.needInitialSkinMatrix) {
  11497. value._registerMeshWithPoseMatrix(this);
  11498. }
  11499. this._skeleton = value;
  11500. if (!this._skeleton) {
  11501. this._bonesTransformMatrices = null;
  11502. }
  11503. this._markSubMeshesAsAttributesDirty();
  11504. },
  11505. enumerable: true,
  11506. configurable: true
  11507. });
  11508. /**
  11509. * Returns the string "AbstractMesh"
  11510. */
  11511. AbstractMesh.prototype.getClassName = function () {
  11512. return "AbstractMesh";
  11513. };
  11514. /**
  11515. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11516. */
  11517. AbstractMesh.prototype.toString = function (fullDetails) {
  11518. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11519. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11520. if (this._skeleton) {
  11521. ret += ", skeleton: " + this._skeleton.name;
  11522. }
  11523. if (fullDetails) {
  11524. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11525. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11526. }
  11527. return ret;
  11528. };
  11529. AbstractMesh.prototype._resyncLightSources = function () {
  11530. this._lightSources.length = 0;
  11531. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11532. var light = _a[_i];
  11533. if (!light.isEnabled()) {
  11534. continue;
  11535. }
  11536. if (light.canAffectMesh(this)) {
  11537. this._lightSources.push(light);
  11538. }
  11539. }
  11540. this._markSubMeshesAsLightDirty();
  11541. };
  11542. AbstractMesh.prototype._resyncLighSource = function (light) {
  11543. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11544. var index = this._lightSources.indexOf(light);
  11545. if (index === -1) {
  11546. if (!isIn) {
  11547. return;
  11548. }
  11549. this._lightSources.push(light);
  11550. }
  11551. else {
  11552. if (isIn) {
  11553. return;
  11554. }
  11555. this._lightSources.splice(index, 1);
  11556. }
  11557. this._markSubMeshesAsLightDirty();
  11558. };
  11559. AbstractMesh.prototype._removeLightSource = function (light) {
  11560. var index = this._lightSources.indexOf(light);
  11561. if (index === -1) {
  11562. return;
  11563. }
  11564. this._lightSources.splice(index, 1);
  11565. };
  11566. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11567. if (!this.subMeshes) {
  11568. return;
  11569. }
  11570. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11571. var subMesh = _a[_i];
  11572. if (subMesh._materialDefines) {
  11573. func(subMesh._materialDefines);
  11574. }
  11575. }
  11576. };
  11577. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11578. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11579. };
  11580. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11581. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11582. };
  11583. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11584. if (!this.subMeshes) {
  11585. return;
  11586. }
  11587. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11588. var subMesh = _a[_i];
  11589. var material = subMesh.getMaterial();
  11590. if (material) {
  11591. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11592. }
  11593. }
  11594. };
  11595. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11596. /**
  11597. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11598. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11599. * Default : (0.0, 0.0, 0.0)
  11600. */
  11601. get: function () {
  11602. return this._rotation;
  11603. },
  11604. set: function (newRotation) {
  11605. this._rotation = newRotation;
  11606. },
  11607. enumerable: true,
  11608. configurable: true
  11609. });
  11610. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11611. /**
  11612. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11613. * Default : (1.0, 1.0, 1.0)
  11614. */
  11615. get: function () {
  11616. return this._scaling;
  11617. },
  11618. set: function (newScaling) {
  11619. this._scaling = newScaling;
  11620. if (this.physicsImpostor) {
  11621. this.physicsImpostor.forceUpdate();
  11622. }
  11623. },
  11624. enumerable: true,
  11625. configurable: true
  11626. });
  11627. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11628. /**
  11629. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11630. * It's null by default.
  11631. * 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)
  11632. */
  11633. get: function () {
  11634. return this._rotationQuaternion;
  11635. },
  11636. set: function (quaternion) {
  11637. this._rotationQuaternion = quaternion;
  11638. //reset the rotation vector.
  11639. if (quaternion && this.rotation.length()) {
  11640. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11641. }
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. // Methods
  11647. /**
  11648. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11649. * Returns the AbstractMesh.
  11650. */
  11651. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11652. this._poseMatrix.copyFrom(matrix);
  11653. return this;
  11654. };
  11655. /**
  11656. * Returns the mesh Pose matrix.
  11657. * Returned object : Matrix
  11658. */
  11659. AbstractMesh.prototype.getPoseMatrix = function () {
  11660. return this._poseMatrix;
  11661. };
  11662. /**
  11663. * Disables the mesh edger rendering mode.
  11664. * Returns the AbstractMesh.
  11665. */
  11666. AbstractMesh.prototype.disableEdgesRendering = function () {
  11667. if (this._edgesRenderer !== undefined) {
  11668. this._edgesRenderer.dispose();
  11669. this._edgesRenderer = undefined;
  11670. }
  11671. return this;
  11672. };
  11673. /**
  11674. * Enables the edge rendering mode on the mesh.
  11675. * This mode makes the mesh edges visible.
  11676. * Returns the AbstractMesh.
  11677. */
  11678. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11679. if (epsilon === void 0) { epsilon = 0.95; }
  11680. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11681. this.disableEdgesRendering();
  11682. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11683. return this;
  11684. };
  11685. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11686. /**
  11687. * Returns true if the mesh is blocked. Used by the class Mesh.
  11688. * Returns the boolean `false` by default.
  11689. */
  11690. get: function () {
  11691. return false;
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. /**
  11697. * Returns the mesh itself by default, used by the class Mesh.
  11698. * Returned type : AbstractMesh
  11699. */
  11700. AbstractMesh.prototype.getLOD = function (camera) {
  11701. return this;
  11702. };
  11703. /**
  11704. * Returns 0 by default, used by the class Mesh.
  11705. * Returns an integer.
  11706. */
  11707. AbstractMesh.prototype.getTotalVertices = function () {
  11708. return 0;
  11709. };
  11710. /**
  11711. * Returns null by default, used by the class Mesh.
  11712. * Returned type : integer array
  11713. */
  11714. AbstractMesh.prototype.getIndices = function () {
  11715. return null;
  11716. };
  11717. /**
  11718. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11719. * Returned type : float array or Float32Array
  11720. */
  11721. AbstractMesh.prototype.getVerticesData = function (kind) {
  11722. return null;
  11723. };
  11724. /**
  11725. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11726. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11727. * The `data` are either a numeric array either a Float32Array.
  11728. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11729. * 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).
  11730. * Note that a new underlying VertexBuffer object is created each call.
  11731. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11732. *
  11733. * Possible `kind` values :
  11734. * - BABYLON.VertexBuffer.PositionKind
  11735. * - BABYLON.VertexBuffer.UVKind
  11736. * - BABYLON.VertexBuffer.UV2Kind
  11737. * - BABYLON.VertexBuffer.UV3Kind
  11738. * - BABYLON.VertexBuffer.UV4Kind
  11739. * - BABYLON.VertexBuffer.UV5Kind
  11740. * - BABYLON.VertexBuffer.UV6Kind
  11741. * - BABYLON.VertexBuffer.ColorKind
  11742. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11743. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11744. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11745. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11746. *
  11747. * Returns the Mesh.
  11748. */
  11749. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11750. return null;
  11751. };
  11752. /**
  11753. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11754. * If the mesh has no geometry, it is simply returned as it is.
  11755. * The `data` are either a numeric array either a Float32Array.
  11756. * No new underlying VertexBuffer object is created.
  11757. * 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.
  11758. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11759. *
  11760. * Possible `kind` values :
  11761. * - BABYLON.VertexBuffer.PositionKind
  11762. * - BABYLON.VertexBuffer.UVKind
  11763. * - BABYLON.VertexBuffer.UV2Kind
  11764. * - BABYLON.VertexBuffer.UV3Kind
  11765. * - BABYLON.VertexBuffer.UV4Kind
  11766. * - BABYLON.VertexBuffer.UV5Kind
  11767. * - BABYLON.VertexBuffer.UV6Kind
  11768. * - BABYLON.VertexBuffer.ColorKind
  11769. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11770. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11771. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11772. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11773. *
  11774. * Returns the Mesh.
  11775. */
  11776. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11777. return null;
  11778. };
  11779. /**
  11780. * Sets the mesh indices.
  11781. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11782. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11783. * This method creates a new index buffer each call.
  11784. * Returns the Mesh.
  11785. */
  11786. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11787. return null;
  11788. };
  11789. /** Returns false by default, used by the class Mesh.
  11790. * Returns a boolean
  11791. */
  11792. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11793. return false;
  11794. };
  11795. /**
  11796. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11797. * Returns a BoundingInfo
  11798. */
  11799. AbstractMesh.prototype.getBoundingInfo = function () {
  11800. if (this._masterMesh) {
  11801. return this._masterMesh.getBoundingInfo();
  11802. }
  11803. if (!this._boundingInfo) {
  11804. this._updateBoundingInfo();
  11805. }
  11806. return this._boundingInfo;
  11807. };
  11808. /**
  11809. * Sets a mesh new object BoundingInfo.
  11810. * Returns the AbstractMesh.
  11811. */
  11812. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11813. this._boundingInfo = boundingInfo;
  11814. return this;
  11815. };
  11816. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11817. get: function () {
  11818. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. AbstractMesh.prototype._preActivate = function () {
  11824. };
  11825. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11826. };
  11827. AbstractMesh.prototype._activate = function (renderId) {
  11828. this._renderId = renderId;
  11829. };
  11830. /**
  11831. * Returns the last update of the World matrix
  11832. * Returns a Matrix.
  11833. */
  11834. AbstractMesh.prototype.getWorldMatrix = function () {
  11835. if (this._masterMesh) {
  11836. return this._masterMesh.getWorldMatrix();
  11837. }
  11838. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11839. this.computeWorldMatrix();
  11840. }
  11841. return this._worldMatrix;
  11842. };
  11843. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11844. /**
  11845. * Returns directly the last state of the mesh World matrix.
  11846. * A Matrix is returned.
  11847. */
  11848. get: function () {
  11849. return this._worldMatrix;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11855. /**
  11856. * Returns the current mesh absolute position.
  11857. * Retuns a Vector3.
  11858. */
  11859. get: function () {
  11860. return this._absolutePosition;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. /**
  11866. * Prevents the World matrix to be computed any longer.
  11867. * Returns the AbstractMesh.
  11868. */
  11869. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11870. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11871. this.computeWorldMatrix(true);
  11872. this._isWorldMatrixFrozen = true;
  11873. return this;
  11874. };
  11875. /**
  11876. * Allows back the World matrix computation.
  11877. * Returns the AbstractMesh.
  11878. */
  11879. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11880. this._isWorldMatrixFrozen = false;
  11881. this.computeWorldMatrix(true);
  11882. return this;
  11883. };
  11884. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11885. /**
  11886. * True if the World matrix has been frozen.
  11887. * Returns a boolean.
  11888. */
  11889. get: function () {
  11890. return this._isWorldMatrixFrozen;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. /**
  11896. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11897. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11898. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11899. * The passed axis is also normalized.
  11900. * Returns the AbstractMesh.
  11901. */
  11902. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11903. axis.normalize();
  11904. if (!this.rotationQuaternion) {
  11905. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11906. this.rotation = BABYLON.Vector3.Zero();
  11907. }
  11908. var rotationQuaternion;
  11909. if (!space || space === BABYLON.Space.LOCAL) {
  11910. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11911. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11912. }
  11913. else {
  11914. if (this.parent) {
  11915. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11916. invertParentWorldMatrix.invert();
  11917. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11918. }
  11919. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11920. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11921. }
  11922. return this;
  11923. };
  11924. /**
  11925. * Translates the mesh along the axis vector for the passed distance in the given space.
  11926. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11927. * Returns the AbstractMesh.
  11928. */
  11929. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11930. var displacementVector = axis.scale(distance);
  11931. if (!space || space === BABYLON.Space.LOCAL) {
  11932. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11933. this.setPositionWithLocalVector(tempV3);
  11934. }
  11935. else {
  11936. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11937. }
  11938. return this;
  11939. };
  11940. /**
  11941. * Adds a rotation step to the mesh current rotation.
  11942. * x, y, z are Euler angles expressed in radians.
  11943. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11944. * This means this rotation is made in the mesh local space only.
  11945. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11946. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11947. * ```javascript
  11948. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11949. * ```
  11950. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11951. * 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.
  11952. * Returns the AbstractMesh.
  11953. */
  11954. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11955. var rotationQuaternion;
  11956. if (this.rotationQuaternion) {
  11957. rotationQuaternion = this.rotationQuaternion;
  11958. }
  11959. else {
  11960. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11961. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11962. }
  11963. var accumulation = BABYLON.Tmp.Quaternion[0];
  11964. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11965. rotationQuaternion.multiplyInPlace(accumulation);
  11966. if (!this.rotationQuaternion) {
  11967. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11968. }
  11969. return this;
  11970. };
  11971. /**
  11972. * Retuns the mesh absolute position in the World.
  11973. * Returns a Vector3.
  11974. */
  11975. AbstractMesh.prototype.getAbsolutePosition = function () {
  11976. this.computeWorldMatrix();
  11977. return this._absolutePosition;
  11978. };
  11979. /**
  11980. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11981. * Returns the AbstractMesh.
  11982. */
  11983. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11984. if (!absolutePosition) {
  11985. return;
  11986. }
  11987. var absolutePositionX;
  11988. var absolutePositionY;
  11989. var absolutePositionZ;
  11990. if (absolutePosition.x === undefined) {
  11991. if (arguments.length < 3) {
  11992. return;
  11993. }
  11994. absolutePositionX = arguments[0];
  11995. absolutePositionY = arguments[1];
  11996. absolutePositionZ = arguments[2];
  11997. }
  11998. else {
  11999. absolutePositionX = absolutePosition.x;
  12000. absolutePositionY = absolutePosition.y;
  12001. absolutePositionZ = absolutePosition.z;
  12002. }
  12003. if (this.parent) {
  12004. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12005. invertParentWorldMatrix.invert();
  12006. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12007. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12008. }
  12009. else {
  12010. this.position.x = absolutePositionX;
  12011. this.position.y = absolutePositionY;
  12012. this.position.z = absolutePositionZ;
  12013. }
  12014. return this;
  12015. };
  12016. // ================================== Point of View Movement =================================
  12017. /**
  12018. * Perform relative position change from the point of view of behind the front of the mesh.
  12019. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12020. * Supports definition of mesh facing forward or backward.
  12021. * @param {number} amountRight
  12022. * @param {number} amountUp
  12023. * @param {number} amountForward
  12024. *
  12025. * Returns the AbstractMesh.
  12026. */
  12027. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12028. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12029. return this;
  12030. };
  12031. /**
  12032. * Calculate relative position change from the point of view of behind the front of the mesh.
  12033. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12034. * Supports definition of mesh facing forward or backward.
  12035. * @param {number} amountRight
  12036. * @param {number} amountUp
  12037. * @param {number} amountForward
  12038. *
  12039. * Returns a new Vector3.
  12040. */
  12041. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12042. var rotMatrix = new BABYLON.Matrix();
  12043. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12044. rotQuaternion.toRotationMatrix(rotMatrix);
  12045. var translationDelta = BABYLON.Vector3.Zero();
  12046. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12047. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12048. return translationDelta;
  12049. };
  12050. // ================================== Point of View Rotation =================================
  12051. /**
  12052. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12053. * Supports definition of mesh facing forward or backward.
  12054. * @param {number} flipBack
  12055. * @param {number} twirlClockwise
  12056. * @param {number} tiltRight
  12057. *
  12058. * Returns the AbstractMesh.
  12059. */
  12060. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12061. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12062. return this;
  12063. };
  12064. /**
  12065. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12066. * Supports definition of mesh facing forward or backward.
  12067. * @param {number} flipBack
  12068. * @param {number} twirlClockwise
  12069. * @param {number} tiltRight
  12070. *
  12071. * Returns a new Vector3.
  12072. */
  12073. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12074. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12075. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12076. };
  12077. /**
  12078. * Sets a new pivot matrix to the mesh.
  12079. * Returns the AbstractMesh.
  12080. */
  12081. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12082. this._pivotMatrix = matrix;
  12083. this._cache.pivotMatrixUpdated = true;
  12084. return this;
  12085. };
  12086. /**
  12087. * Returns the mesh pivot matrix.
  12088. * Default : Identity.
  12089. * A Matrix is returned.
  12090. */
  12091. AbstractMesh.prototype.getPivotMatrix = function () {
  12092. return this._pivotMatrix;
  12093. };
  12094. AbstractMesh.prototype._isSynchronized = function () {
  12095. if (this._isDirty) {
  12096. return false;
  12097. }
  12098. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12099. return false;
  12100. if (this._cache.pivotMatrixUpdated) {
  12101. return false;
  12102. }
  12103. if (this.infiniteDistance) {
  12104. return false;
  12105. }
  12106. if (!this._cache.position.equals(this.position))
  12107. return false;
  12108. if (this.rotationQuaternion) {
  12109. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12110. return false;
  12111. }
  12112. if (!this._cache.rotation.equals(this.rotation))
  12113. return false;
  12114. if (!this._cache.scaling.equals(this.scaling))
  12115. return false;
  12116. return true;
  12117. };
  12118. AbstractMesh.prototype._initCache = function () {
  12119. _super.prototype._initCache.call(this);
  12120. this._cache.localMatrixUpdated = false;
  12121. this._cache.position = BABYLON.Vector3.Zero();
  12122. this._cache.scaling = BABYLON.Vector3.Zero();
  12123. this._cache.rotation = BABYLON.Vector3.Zero();
  12124. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12125. this._cache.billboardMode = -1;
  12126. };
  12127. AbstractMesh.prototype.markAsDirty = function (property) {
  12128. if (property === "rotation") {
  12129. this.rotationQuaternion = null;
  12130. }
  12131. this._currentRenderId = Number.MAX_VALUE;
  12132. this._isDirty = true;
  12133. return this;
  12134. };
  12135. /**
  12136. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12137. * Returns the AbstractMesh.
  12138. */
  12139. AbstractMesh.prototype._updateBoundingInfo = function () {
  12140. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12141. this._boundingInfo.update(this.worldMatrixFromCache);
  12142. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12143. return this;
  12144. };
  12145. /**
  12146. * Update a mesh's children BoundingInfo objects only.
  12147. * Returns the AbstractMesh.
  12148. */
  12149. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12150. if (!this.subMeshes) {
  12151. return;
  12152. }
  12153. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12154. var subMesh = this.subMeshes[subIndex];
  12155. if (!subMesh.IsGlobal) {
  12156. subMesh.updateBoundingInfo(matrix);
  12157. }
  12158. }
  12159. return this;
  12160. };
  12161. /**
  12162. * Computes the mesh World matrix and returns it.
  12163. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12164. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12165. * If the parameter `force`is set to `true`, the actual computation is done.
  12166. * Returns the mesh World Matrix.
  12167. */
  12168. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12169. if (this._isWorldMatrixFrozen) {
  12170. return this._worldMatrix;
  12171. }
  12172. if (!force && this.isSynchronized(true)) {
  12173. this._currentRenderId = this.getScene().getRenderId();
  12174. return this._worldMatrix;
  12175. }
  12176. this._cache.position.copyFrom(this.position);
  12177. this._cache.scaling.copyFrom(this.scaling);
  12178. this._cache.pivotMatrixUpdated = false;
  12179. this._cache.billboardMode = this.billboardMode;
  12180. this._currentRenderId = this.getScene().getRenderId();
  12181. this._isDirty = false;
  12182. // Scaling
  12183. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12184. // Rotation
  12185. //rotate, if quaternion is set and rotation was used
  12186. if (this.rotationQuaternion) {
  12187. var len = this.rotation.length();
  12188. if (len) {
  12189. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12190. this.rotation.copyFromFloats(0, 0, 0);
  12191. }
  12192. }
  12193. if (this.rotationQuaternion) {
  12194. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12195. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12196. }
  12197. else {
  12198. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12199. this._cache.rotation.copyFrom(this.rotation);
  12200. }
  12201. // Translation
  12202. if (this.infiniteDistance && !this.parent) {
  12203. var camera = this.getScene().activeCamera;
  12204. if (camera) {
  12205. var cameraWorldMatrix = camera.getWorldMatrix();
  12206. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12207. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12208. }
  12209. }
  12210. else {
  12211. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12212. }
  12213. // Composing transformations
  12214. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12215. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12216. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12217. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12218. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12219. // Need to decompose each rotation here
  12220. var currentPosition = BABYLON.Tmp.Vector3[3];
  12221. if (this.parent && this.parent.getWorldMatrix) {
  12222. if (this._meshToBoneReferal) {
  12223. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12224. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12225. }
  12226. else {
  12227. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12228. }
  12229. }
  12230. else {
  12231. currentPosition.copyFrom(this.position);
  12232. }
  12233. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12234. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12235. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12236. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12237. }
  12238. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12239. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12240. }
  12241. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12242. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12243. }
  12244. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12245. }
  12246. else {
  12247. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12248. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12249. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12250. }
  12251. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12252. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12253. }
  12254. // Local world
  12255. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12256. // Parent
  12257. if (this.parent && this.parent.getWorldMatrix) {
  12258. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12259. if (this._meshToBoneReferal) {
  12260. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12261. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12262. }
  12263. else {
  12264. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12265. }
  12266. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12267. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12268. this._worldMatrix.copyFrom(this._localWorld);
  12269. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12270. }
  12271. else {
  12272. if (this._meshToBoneReferal) {
  12273. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12274. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12275. }
  12276. else {
  12277. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12278. }
  12279. }
  12280. this._markSyncedWithParent();
  12281. }
  12282. else {
  12283. this._worldMatrix.copyFrom(this._localWorld);
  12284. }
  12285. // Bounding info
  12286. this._updateBoundingInfo();
  12287. // Absolute position
  12288. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12289. // Callbacks
  12290. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12291. if (!this._poseMatrix) {
  12292. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12293. }
  12294. return this._worldMatrix;
  12295. };
  12296. /**
  12297. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12298. * @param func: callback function to add
  12299. *
  12300. * Returns the AbstractMesh.
  12301. */
  12302. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12303. this.onAfterWorldMatrixUpdateObservable.add(func);
  12304. return this;
  12305. };
  12306. /**
  12307. * Removes a registered callback function.
  12308. * Returns the AbstractMesh.
  12309. */
  12310. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12311. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12312. return this;
  12313. };
  12314. /**
  12315. * Sets the mesh position in its local space.
  12316. * Returns the AbstractMesh.
  12317. */
  12318. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12319. this.computeWorldMatrix();
  12320. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12321. return this;
  12322. };
  12323. /**
  12324. * Returns the mesh position in the local space from the current World matrix values.
  12325. * Returns a new Vector3.
  12326. */
  12327. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12328. this.computeWorldMatrix();
  12329. var invLocalWorldMatrix = this._localWorld.clone();
  12330. invLocalWorldMatrix.invert();
  12331. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12332. };
  12333. /**
  12334. * Translates the mesh along the passed Vector3 in its local space.
  12335. * Returns the AbstractMesh.
  12336. */
  12337. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12338. this.computeWorldMatrix(true);
  12339. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12340. return this;
  12341. };
  12342. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12343. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12344. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12345. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12346. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12347. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12348. /// <returns>Mesh oriented towards targetMesh</returns>
  12349. if (yawCor === void 0) { yawCor = 0; }
  12350. if (pitchCor === void 0) { pitchCor = 0; }
  12351. if (rollCor === void 0) { rollCor = 0; }
  12352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12353. var dv = AbstractMesh._lookAtVectorCache;
  12354. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12355. targetPoint.subtractToRef(pos, dv);
  12356. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12357. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12358. var pitch = Math.atan2(dv.y, len);
  12359. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12360. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12361. return this;
  12362. };
  12363. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12364. this._meshToBoneReferal = affectedMesh;
  12365. this.parent = bone;
  12366. if (bone.getWorldMatrix().determinant() < 0) {
  12367. this.scalingDeterminant *= -1;
  12368. }
  12369. return this;
  12370. };
  12371. AbstractMesh.prototype.detachFromBone = function () {
  12372. if (this.parent.getWorldMatrix().determinant() < 0) {
  12373. this.scalingDeterminant *= -1;
  12374. }
  12375. this._meshToBoneReferal = null;
  12376. this.parent = null;
  12377. return this;
  12378. };
  12379. /**
  12380. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12381. * A mesh is in the frustum if its bounding box intersects the frustum.
  12382. * Boolean returned.
  12383. */
  12384. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12385. return this._boundingInfo.isInFrustum(frustumPlanes);
  12386. };
  12387. /**
  12388. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12389. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12390. * Boolean returned.
  12391. */
  12392. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12393. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12394. ;
  12395. };
  12396. /**
  12397. * True if the mesh intersects another mesh or a SolidParticle object.
  12398. * 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)
  12399. * Returns a boolean.
  12400. */
  12401. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12402. if (!this._boundingInfo || !mesh._boundingInfo) {
  12403. return false;
  12404. }
  12405. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12406. };
  12407. /**
  12408. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12409. * Returns a boolean.
  12410. */
  12411. AbstractMesh.prototype.intersectsPoint = function (point) {
  12412. if (!this._boundingInfo) {
  12413. return false;
  12414. }
  12415. return this._boundingInfo.intersectsPoint(point);
  12416. };
  12417. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12418. return this.physicsImpostor;
  12419. };
  12420. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12421. if (!camera) {
  12422. camera = this.getScene().activeCamera;
  12423. }
  12424. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12425. };
  12426. /**
  12427. * Returns the distance from the mesh to the active camera.
  12428. * Returns a float.
  12429. */
  12430. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12431. if (!camera) {
  12432. camera = this.getScene().activeCamera;
  12433. }
  12434. return this.absolutePosition.subtract(camera.position).length();
  12435. };
  12436. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12437. if (!this.physicsImpostor) {
  12438. return;
  12439. }
  12440. this.physicsImpostor.applyImpulse(force, contactPoint);
  12441. return this;
  12442. };
  12443. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12444. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12445. return;
  12446. }
  12447. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12448. mainPivot: pivot1,
  12449. connectedPivot: pivot2,
  12450. nativeParams: options
  12451. });
  12452. return this;
  12453. };
  12454. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12455. // Collisions
  12456. /**
  12457. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12458. * Default `false`.
  12459. */
  12460. get: function () {
  12461. return this._checkCollisions;
  12462. },
  12463. set: function (collisionEnabled) {
  12464. this._checkCollisions = collisionEnabled;
  12465. if (this.getScene().workerCollisions) {
  12466. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12467. }
  12468. },
  12469. enumerable: true,
  12470. configurable: true
  12471. });
  12472. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12473. var globalPosition = this.getAbsolutePosition();
  12474. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12475. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12476. if (!this._collider) {
  12477. this._collider = new BABYLON.Collider();
  12478. }
  12479. this._collider.radius = this.ellipsoid;
  12480. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12481. return this;
  12482. };
  12483. // Submeshes octree
  12484. /**
  12485. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12486. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12487. * Returns an Octree of submeshes.
  12488. */
  12489. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12490. if (maxCapacity === void 0) { maxCapacity = 64; }
  12491. if (maxDepth === void 0) { maxDepth = 2; }
  12492. if (!this._submeshesOctree) {
  12493. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12494. }
  12495. this.computeWorldMatrix(true);
  12496. // Update octree
  12497. var bbox = this.getBoundingInfo().boundingBox;
  12498. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12499. return this._submeshesOctree;
  12500. };
  12501. // Collisions
  12502. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12503. this._generatePointsArray();
  12504. // Transformation
  12505. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12506. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12507. subMesh._lastColliderWorldVertices = [];
  12508. subMesh._trianglePlanes = [];
  12509. var start = subMesh.verticesStart;
  12510. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12511. for (var i = start; i < end; i++) {
  12512. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12513. }
  12514. }
  12515. // Collide
  12516. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12517. if (collider.collisionFound) {
  12518. collider.collidedMesh = this;
  12519. }
  12520. return this;
  12521. };
  12522. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12523. var subMeshes;
  12524. var len;
  12525. // Octrees
  12526. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12527. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12528. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12529. len = intersections.length;
  12530. subMeshes = intersections.data;
  12531. }
  12532. else {
  12533. subMeshes = this.subMeshes;
  12534. len = subMeshes.length;
  12535. }
  12536. for (var index = 0; index < len; index++) {
  12537. var subMesh = subMeshes[index];
  12538. // Bounding test
  12539. if (len > 1 && !subMesh._checkCollision(collider))
  12540. continue;
  12541. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12542. }
  12543. return this;
  12544. };
  12545. AbstractMesh.prototype._checkCollision = function (collider) {
  12546. // Bounding box test
  12547. if (!this._boundingInfo._checkCollision(collider))
  12548. return this;
  12549. // Transformation matrix
  12550. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12551. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12552. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12553. return this;
  12554. };
  12555. // Picking
  12556. AbstractMesh.prototype._generatePointsArray = function () {
  12557. return false;
  12558. };
  12559. /**
  12560. * Checks if the passed Ray intersects with the mesh.
  12561. * Returns an object PickingInfo.
  12562. */
  12563. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12564. var pickingInfo = new BABYLON.PickingInfo();
  12565. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12566. return pickingInfo;
  12567. }
  12568. if (!this._generatePointsArray()) {
  12569. return pickingInfo;
  12570. }
  12571. var intersectInfo = null;
  12572. // Octrees
  12573. var subMeshes;
  12574. var len;
  12575. if (this._submeshesOctree && this.useOctreeForPicking) {
  12576. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12577. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12578. len = intersections.length;
  12579. subMeshes = intersections.data;
  12580. }
  12581. else {
  12582. subMeshes = this.subMeshes;
  12583. len = subMeshes.length;
  12584. }
  12585. for (var index = 0; index < len; index++) {
  12586. var subMesh = subMeshes[index];
  12587. // Bounding test
  12588. if (len > 1 && !subMesh.canIntersects(ray))
  12589. continue;
  12590. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12591. if (currentIntersectInfo) {
  12592. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12593. intersectInfo = currentIntersectInfo;
  12594. intersectInfo.subMeshId = index;
  12595. if (fastCheck) {
  12596. break;
  12597. }
  12598. }
  12599. }
  12600. }
  12601. if (intersectInfo) {
  12602. // Get picked point
  12603. var world = this.getWorldMatrix();
  12604. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12605. var direction = ray.direction.clone();
  12606. direction = direction.scale(intersectInfo.distance);
  12607. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12608. var pickedPoint = worldOrigin.add(worldDirection);
  12609. // Return result
  12610. pickingInfo.hit = true;
  12611. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12612. pickingInfo.pickedPoint = pickedPoint;
  12613. pickingInfo.pickedMesh = this;
  12614. pickingInfo.bu = intersectInfo.bu;
  12615. pickingInfo.bv = intersectInfo.bv;
  12616. pickingInfo.faceId = intersectInfo.faceId;
  12617. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12618. return pickingInfo;
  12619. }
  12620. return pickingInfo;
  12621. };
  12622. /**
  12623. * Clones the mesh, used by the class Mesh.
  12624. * Just returns `null` for an AbstractMesh.
  12625. */
  12626. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12627. return null;
  12628. };
  12629. /**
  12630. * Disposes all the mesh submeshes.
  12631. * Returns the AbstractMesh.
  12632. */
  12633. AbstractMesh.prototype.releaseSubMeshes = function () {
  12634. if (this.subMeshes) {
  12635. while (this.subMeshes.length) {
  12636. this.subMeshes[0].dispose();
  12637. }
  12638. }
  12639. else {
  12640. this.subMeshes = new Array();
  12641. }
  12642. return this;
  12643. };
  12644. /**
  12645. * Disposes the AbstractMesh.
  12646. * Some internal references are kept for further use.
  12647. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12648. * Returns nothing.
  12649. */
  12650. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12651. var _this = this;
  12652. var index;
  12653. // Action manager
  12654. if (this.actionManager) {
  12655. this.actionManager.dispose();
  12656. this.actionManager = null;
  12657. }
  12658. // Skeleton
  12659. this.skeleton = null;
  12660. // Animations
  12661. this.getScene().stopAnimation(this);
  12662. // Physics
  12663. if (this.physicsImpostor) {
  12664. this.physicsImpostor.dispose();
  12665. }
  12666. // Intersections in progress
  12667. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12668. var other = this._intersectionsInProgress[index];
  12669. var pos = other._intersectionsInProgress.indexOf(this);
  12670. other._intersectionsInProgress.splice(pos, 1);
  12671. }
  12672. this._intersectionsInProgress = [];
  12673. // Lights
  12674. var lights = this.getScene().lights;
  12675. lights.forEach(function (light) {
  12676. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12677. if (meshIndex !== -1) {
  12678. light.includedOnlyMeshes.splice(meshIndex, 1);
  12679. }
  12680. meshIndex = light.excludedMeshes.indexOf(_this);
  12681. if (meshIndex !== -1) {
  12682. light.excludedMeshes.splice(meshIndex, 1);
  12683. }
  12684. // Shadow generators
  12685. var generator = light.getShadowGenerator();
  12686. if (generator) {
  12687. var shadowMap = generator.getShadowMap();
  12688. meshIndex = shadowMap.renderList.indexOf(_this);
  12689. if (meshIndex !== -1) {
  12690. shadowMap.renderList.splice(meshIndex, 1);
  12691. }
  12692. }
  12693. });
  12694. // Edges
  12695. if (this._edgesRenderer) {
  12696. this._edgesRenderer.dispose();
  12697. this._edgesRenderer = null;
  12698. }
  12699. // SubMeshes
  12700. if (this.getClassName() !== "InstancedMesh") {
  12701. this.releaseSubMeshes();
  12702. }
  12703. // Octree
  12704. var sceneOctree = this.getScene().selectionOctree;
  12705. if (sceneOctree) {
  12706. var index = sceneOctree.dynamicContent.indexOf(this);
  12707. if (index !== -1) {
  12708. sceneOctree.dynamicContent.splice(index, 1);
  12709. }
  12710. }
  12711. // Engine
  12712. this.getScene().getEngine().wipeCaches();
  12713. // Remove from scene
  12714. this.getScene().removeMesh(this);
  12715. if (!doNotRecurse) {
  12716. // Particles
  12717. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12718. if (this.getScene().particleSystems[index].emitter === this) {
  12719. this.getScene().particleSystems[index].dispose();
  12720. index--;
  12721. }
  12722. }
  12723. // Children
  12724. var objects = this.getDescendants(true);
  12725. for (index = 0; index < objects.length; index++) {
  12726. objects[index].dispose();
  12727. }
  12728. }
  12729. else {
  12730. var childMeshes = this.getChildMeshes(true);
  12731. for (index = 0; index < childMeshes.length; index++) {
  12732. var child = childMeshes[index];
  12733. child.parent = null;
  12734. child.computeWorldMatrix(true);
  12735. }
  12736. }
  12737. // facet data
  12738. if (this._facetDataEnabled) {
  12739. this.disableFacetData();
  12740. }
  12741. this.onAfterWorldMatrixUpdateObservable.clear();
  12742. this.onCollideObservable.clear();
  12743. this.onCollisionPositionChangeObservable.clear();
  12744. this._isDisposed = true;
  12745. _super.prototype.dispose.call(this);
  12746. };
  12747. /**
  12748. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12749. * This Vector3 is expressed in the World space.
  12750. */
  12751. AbstractMesh.prototype.getDirection = function (localAxis) {
  12752. var result = BABYLON.Vector3.Zero();
  12753. this.getDirectionToRef(localAxis, result);
  12754. return result;
  12755. };
  12756. /**
  12757. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12758. * localAxis is expressed in the mesh local space.
  12759. * result is computed in the Wordl space from the mesh World matrix.
  12760. * Returns the AbstractMesh.
  12761. */
  12762. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12763. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12764. return this;
  12765. };
  12766. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12768. if (this.getScene().getRenderId() == 0) {
  12769. this.computeWorldMatrix(true);
  12770. }
  12771. var wm = this.getWorldMatrix();
  12772. if (space == BABYLON.Space.WORLD) {
  12773. var tmat = BABYLON.Tmp.Matrix[0];
  12774. wm.invertToRef(tmat);
  12775. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12776. }
  12777. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12778. this._pivotMatrix.m[12] = -point.x;
  12779. this._pivotMatrix.m[13] = -point.y;
  12780. this._pivotMatrix.m[14] = -point.z;
  12781. this._cache.pivotMatrixUpdated = true;
  12782. return this;
  12783. };
  12784. /**
  12785. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12786. */
  12787. AbstractMesh.prototype.getPivotPoint = function () {
  12788. var point = BABYLON.Vector3.Zero();
  12789. this.getPivotPointToRef(point);
  12790. return point;
  12791. };
  12792. /**
  12793. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12794. * Returns the AbstractMesh.
  12795. */
  12796. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12797. result.x = -this._pivotMatrix.m[12];
  12798. result.y = -this._pivotMatrix.m[13];
  12799. result.z = -this._pivotMatrix.m[14];
  12800. return this;
  12801. };
  12802. /**
  12803. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12804. */
  12805. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12806. var point = BABYLON.Vector3.Zero();
  12807. this.getAbsolutePivotPointToRef(point);
  12808. return point;
  12809. };
  12810. /**
  12811. * Defines the passed mesh as the parent of the current mesh.
  12812. * Returns the AbstractMesh.
  12813. */
  12814. AbstractMesh.prototype.setParent = function (mesh) {
  12815. var child = this;
  12816. var parent = mesh;
  12817. if (mesh == null) {
  12818. var rotation = BABYLON.Tmp.Quaternion[0];
  12819. var position = BABYLON.Tmp.Vector3[0];
  12820. var scale = BABYLON.Tmp.Vector3[1];
  12821. child.getWorldMatrix().decompose(scale, rotation, position);
  12822. if (child.rotationQuaternion) {
  12823. child.rotationQuaternion.copyFrom(rotation);
  12824. }
  12825. else {
  12826. rotation.toEulerAnglesToRef(child.rotation);
  12827. }
  12828. child.position.x = position.x;
  12829. child.position.y = position.y;
  12830. child.position.z = position.z;
  12831. }
  12832. else {
  12833. var rotation = BABYLON.Tmp.Quaternion[0];
  12834. var position = BABYLON.Tmp.Vector3[0];
  12835. var scale = BABYLON.Tmp.Vector3[1];
  12836. var m1 = BABYLON.Tmp.Matrix[0];
  12837. var m2 = BABYLON.Tmp.Matrix[1];
  12838. parent.getWorldMatrix().decompose(scale, rotation, position);
  12839. rotation.toRotationMatrix(m1);
  12840. m2.setTranslation(position);
  12841. m2.multiplyToRef(m1, m1);
  12842. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12843. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12844. m.decompose(scale, rotation, position);
  12845. if (child.rotationQuaternion) {
  12846. child.rotationQuaternion.copyFrom(rotation);
  12847. }
  12848. else {
  12849. rotation.toEulerAnglesToRef(child.rotation);
  12850. }
  12851. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12852. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12853. m.decompose(scale, rotation, position);
  12854. child.position.x = position.x;
  12855. child.position.y = position.y;
  12856. child.position.z = position.z;
  12857. }
  12858. child.parent = parent;
  12859. return this;
  12860. };
  12861. /**
  12862. * Adds the passed mesh as a child to the current mesh.
  12863. * Returns the AbstractMesh.
  12864. */
  12865. AbstractMesh.prototype.addChild = function (mesh) {
  12866. mesh.setParent(this);
  12867. return this;
  12868. };
  12869. /**
  12870. * Removes the passed mesh from the current mesh children list.
  12871. * Returns the AbstractMesh.
  12872. */
  12873. AbstractMesh.prototype.removeChild = function (mesh) {
  12874. mesh.setParent(null);
  12875. return this;
  12876. };
  12877. /**
  12878. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12879. * Returns the AbstractMesh.
  12880. */
  12881. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12882. result.x = this._pivotMatrix.m[12];
  12883. result.y = this._pivotMatrix.m[13];
  12884. result.z = this._pivotMatrix.m[14];
  12885. this.getPivotPointToRef(result);
  12886. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12887. return this;
  12888. };
  12889. // Facet data
  12890. /**
  12891. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12892. * Returns the AbstractMesh.
  12893. */
  12894. AbstractMesh.prototype._initFacetData = function () {
  12895. if (!this._facetNormals) {
  12896. this._facetNormals = new Array();
  12897. }
  12898. if (!this._facetPositions) {
  12899. this._facetPositions = new Array();
  12900. }
  12901. if (!this._facetPartitioning) {
  12902. this._facetPartitioning = new Array();
  12903. }
  12904. this._facetNb = this.getIndices().length / 3;
  12905. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12906. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12907. for (var f = 0; f < this._facetNb; f++) {
  12908. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12909. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12910. }
  12911. this._facetDataEnabled = true;
  12912. return this;
  12913. };
  12914. /**
  12915. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12916. * This method can be called within the render loop.
  12917. * 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.
  12918. * Returns the AbstractMesh.
  12919. */
  12920. AbstractMesh.prototype.updateFacetData = function () {
  12921. if (!this._facetDataEnabled) {
  12922. this._initFacetData();
  12923. }
  12924. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12925. var indices = this.getIndices();
  12926. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12927. var bInfo = this.getBoundingInfo();
  12928. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12929. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12930. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12931. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12932. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12933. this._subDiv.max = this._partitioningSubdivisions;
  12934. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12935. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12936. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12937. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12938. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12939. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12940. // set the parameters for ComputeNormals()
  12941. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12942. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12943. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12944. this._facetParameters.bInfo = bInfo;
  12945. this._facetParameters.bbSize = this._bbSize;
  12946. this._facetParameters.subDiv = this._subDiv;
  12947. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12948. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12949. return this;
  12950. };
  12951. /**
  12952. * Returns the facetLocalNormals array.
  12953. * The normals are expressed in the mesh local space.
  12954. */
  12955. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12956. if (!this._facetNormals) {
  12957. this.updateFacetData();
  12958. }
  12959. return this._facetNormals;
  12960. };
  12961. /**
  12962. * Returns the facetLocalPositions array.
  12963. * The facet positions are expressed in the mesh local space.
  12964. */
  12965. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12966. if (!this._facetPositions) {
  12967. this.updateFacetData();
  12968. }
  12969. return this._facetPositions;
  12970. };
  12971. /**
  12972. * Returns the facetLocalPartioning array.
  12973. */
  12974. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12975. if (!this._facetPartitioning) {
  12976. this.updateFacetData();
  12977. }
  12978. return this._facetPartitioning;
  12979. };
  12980. /**
  12981. * Returns the i-th facet position in the world system.
  12982. * This method allocates a new Vector3 per call.
  12983. */
  12984. AbstractMesh.prototype.getFacetPosition = function (i) {
  12985. var pos = BABYLON.Vector3.Zero();
  12986. this.getFacetPositionToRef(i, pos);
  12987. return pos;
  12988. };
  12989. /**
  12990. * Sets the reference Vector3 with the i-th facet position in the world system.
  12991. * Returns the AbstractMesh.
  12992. */
  12993. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12994. var localPos = (this.getFacetLocalPositions())[i];
  12995. var world = this.getWorldMatrix();
  12996. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12997. return this;
  12998. };
  12999. /**
  13000. * Returns the i-th facet normal in the world system.
  13001. * This method allocates a new Vector3 per call.
  13002. */
  13003. AbstractMesh.prototype.getFacetNormal = function (i) {
  13004. var norm = BABYLON.Vector3.Zero();
  13005. this.getFacetNormalToRef(i, norm);
  13006. return norm;
  13007. };
  13008. /**
  13009. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13010. * Returns the AbstractMesh.
  13011. */
  13012. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13013. var localNorm = (this.getFacetLocalNormals())[i];
  13014. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13015. return this;
  13016. };
  13017. /**
  13018. * 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).
  13019. */
  13020. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13021. var bInfo = this.getBoundingInfo();
  13022. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13023. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13024. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13025. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13026. return null;
  13027. }
  13028. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13029. };
  13030. /**
  13031. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13032. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13033. * 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.
  13034. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13035. * 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.
  13036. */
  13037. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13038. if (checkFace === void 0) { checkFace = false; }
  13039. if (facing === void 0) { facing = true; }
  13040. var world = this.getWorldMatrix();
  13041. var invMat = BABYLON.Tmp.Matrix[5];
  13042. world.invertToRef(invMat);
  13043. var invVect = BABYLON.Tmp.Vector3[8];
  13044. var closest = null;
  13045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13046. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13047. if (projected) {
  13048. // tranform the local computed projected vector to world coordinates
  13049. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13050. }
  13051. return closest;
  13052. };
  13053. /**
  13054. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13055. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13056. * 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.
  13057. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13058. * 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.
  13059. */
  13060. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13061. if (checkFace === void 0) { checkFace = false; }
  13062. if (facing === void 0) { facing = true; }
  13063. var closest = null;
  13064. var tmpx = 0.0;
  13065. var tmpy = 0.0;
  13066. var tmpz = 0.0;
  13067. var d = 0.0; // tmp dot facet normal * facet position
  13068. var t0 = 0.0;
  13069. var projx = 0.0;
  13070. var projy = 0.0;
  13071. var projz = 0.0;
  13072. // Get all the facets in the same partitioning block than (x, y, z)
  13073. var facetPositions = this.getFacetLocalPositions();
  13074. var facetNormals = this.getFacetLocalNormals();
  13075. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13076. if (!facetsInBlock) {
  13077. return null;
  13078. }
  13079. // Get the closest facet to (x, y, z)
  13080. var shortest = Number.MAX_VALUE; // init distance vars
  13081. var tmpDistance = shortest;
  13082. var fib; // current facet in the block
  13083. var norm; // current facet normal
  13084. var p0; // current facet barycenter position
  13085. // loop on all the facets in the current partitioning block
  13086. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13087. fib = facetsInBlock[idx];
  13088. norm = facetNormals[fib];
  13089. p0 = facetPositions[fib];
  13090. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13091. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13092. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13093. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13094. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13095. projx = x + norm.x * t0;
  13096. projy = y + norm.y * t0;
  13097. projz = z + norm.z * t0;
  13098. tmpx = projx - x;
  13099. tmpy = projy - y;
  13100. tmpz = projz - z;
  13101. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13102. if (tmpDistance < shortest) {
  13103. shortest = tmpDistance;
  13104. closest = fib;
  13105. if (projected) {
  13106. projected.x = projx;
  13107. projected.y = projy;
  13108. projected.z = projz;
  13109. }
  13110. }
  13111. }
  13112. }
  13113. return closest;
  13114. };
  13115. /**
  13116. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13117. */
  13118. AbstractMesh.prototype.getFacetDataParameters = function () {
  13119. return this._facetParameters;
  13120. };
  13121. /**
  13122. * Disables the feature FacetData and frees the related memory.
  13123. * Returns the AbstractMesh.
  13124. */
  13125. AbstractMesh.prototype.disableFacetData = function () {
  13126. if (this._facetDataEnabled) {
  13127. this._facetDataEnabled = false;
  13128. this._facetPositions = null;
  13129. this._facetNormals = null;
  13130. this._facetPartitioning = null;
  13131. this._facetParameters = null;
  13132. }
  13133. return this;
  13134. };
  13135. /**
  13136. * Creates new normals data for the mesh.
  13137. * @param updatable.
  13138. */
  13139. AbstractMesh.prototype.createNormals = function (updatable) {
  13140. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13141. var indices = this.getIndices();
  13142. var normals;
  13143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13144. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13145. }
  13146. else {
  13147. normals = [];
  13148. }
  13149. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13150. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13151. };
  13152. return AbstractMesh;
  13153. }(BABYLON.Node));
  13154. // Statics
  13155. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13156. AbstractMesh._BILLBOARDMODE_X = 1;
  13157. AbstractMesh._BILLBOARDMODE_Y = 2;
  13158. AbstractMesh._BILLBOARDMODE_Z = 4;
  13159. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13160. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13161. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13162. BABYLON.AbstractMesh = AbstractMesh;
  13163. })(BABYLON || (BABYLON = {}));
  13164. //# sourceMappingURL=babylon.abstractMesh.js.map
  13165. var BABYLON;
  13166. (function (BABYLON) {
  13167. var Light = (function (_super) {
  13168. __extends(Light, _super);
  13169. /**
  13170. * Creates a Light object in the scene.
  13171. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13172. */
  13173. function Light(name, scene) {
  13174. var _this = _super.call(this, name, scene) || this;
  13175. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13176. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13177. _this.intensity = 1.0;
  13178. _this.range = Number.MAX_VALUE;
  13179. /**
  13180. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13181. * of light.
  13182. */
  13183. _this._photometricScale = 1.0;
  13184. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13185. _this._radius = 0.00001;
  13186. _this.renderPriority = 0;
  13187. /**
  13188. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13189. * the current shadow generator.
  13190. */
  13191. _this.shadowEnabled = true;
  13192. _this._excludeWithLayerMask = 0;
  13193. _this._includeOnlyWithLayerMask = 0;
  13194. _this._lightmapMode = 0;
  13195. _this._excludedMeshesIds = new Array();
  13196. _this._includedOnlyMeshesIds = new Array();
  13197. _this.getScene().addLight(_this);
  13198. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13199. _this._buildUniformLayout();
  13200. _this.includedOnlyMeshes = new Array();
  13201. _this.excludedMeshes = new Array();
  13202. _this._resyncMeshes();
  13203. return _this;
  13204. }
  13205. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13206. /**
  13207. * If every light affecting the material is in this lightmapMode,
  13208. * material.lightmapTexture adds or multiplies
  13209. * (depends on material.useLightmapAsShadowmap)
  13210. * after every other light calculations.
  13211. */
  13212. get: function () {
  13213. return Light._LIGHTMAP_DEFAULT;
  13214. },
  13215. enumerable: true,
  13216. configurable: true
  13217. });
  13218. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13219. /**
  13220. * material.lightmapTexture as only diffuse lighting from this light
  13221. * adds pnly specular lighting from this light
  13222. * adds dynamic shadows
  13223. */
  13224. get: function () {
  13225. return Light._LIGHTMAP_SPECULAR;
  13226. },
  13227. enumerable: true,
  13228. configurable: true
  13229. });
  13230. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13231. /**
  13232. * material.lightmapTexture as only lighting
  13233. * no light calculation from this light
  13234. * only adds dynamic shadows from this light
  13235. */
  13236. get: function () {
  13237. return Light._LIGHTMAP_SHADOWSONLY;
  13238. },
  13239. enumerable: true,
  13240. configurable: true
  13241. });
  13242. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13243. /**
  13244. * Each light type uses the default quantity according to its type:
  13245. * point/spot lights use luminous intensity
  13246. * directional lights use illuminance
  13247. */
  13248. get: function () {
  13249. return Light._INTENSITYMODE_AUTOMATIC;
  13250. },
  13251. enumerable: true,
  13252. configurable: true
  13253. });
  13254. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13255. /**
  13256. * lumen (lm)
  13257. */
  13258. get: function () {
  13259. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13260. },
  13261. enumerable: true,
  13262. configurable: true
  13263. });
  13264. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13265. /**
  13266. * candela (lm/sr)
  13267. */
  13268. get: function () {
  13269. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13270. },
  13271. enumerable: true,
  13272. configurable: true
  13273. });
  13274. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13275. /**
  13276. * lux (lm/m^2)
  13277. */
  13278. get: function () {
  13279. return Light._INTENSITYMODE_ILLUMINANCE;
  13280. },
  13281. enumerable: true,
  13282. configurable: true
  13283. });
  13284. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13285. /**
  13286. * nit (cd/m^2)
  13287. */
  13288. get: function () {
  13289. return Light._INTENSITYMODE_LUMINANCE;
  13290. },
  13291. enumerable: true,
  13292. configurable: true
  13293. });
  13294. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13295. /**
  13296. * Light type const id of the point light.
  13297. */
  13298. get: function () {
  13299. return Light._LIGHTTYPEID_POINTLIGHT;
  13300. },
  13301. enumerable: true,
  13302. configurable: true
  13303. });
  13304. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13305. /**
  13306. * Light type const id of the directional light.
  13307. */
  13308. get: function () {
  13309. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13310. },
  13311. enumerable: true,
  13312. configurable: true
  13313. });
  13314. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13315. /**
  13316. * Light type const id of the spot light.
  13317. */
  13318. get: function () {
  13319. return Light._LIGHTTYPEID_SPOTLIGHT;
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13325. /**
  13326. * Light type const id of the hemispheric light.
  13327. */
  13328. get: function () {
  13329. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13330. },
  13331. enumerable: true,
  13332. configurable: true
  13333. });
  13334. Object.defineProperty(Light.prototype, "intensityMode", {
  13335. /**
  13336. * Gets the photometric scale used to interpret the intensity.
  13337. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13338. */
  13339. get: function () {
  13340. return this._intensityMode;
  13341. },
  13342. /**
  13343. * Sets the photometric scale used to interpret the intensity.
  13344. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13345. */
  13346. set: function (value) {
  13347. this._intensityMode = value;
  13348. this._computePhotometricScale();
  13349. },
  13350. enumerable: true,
  13351. configurable: true
  13352. });
  13353. ;
  13354. ;
  13355. Object.defineProperty(Light.prototype, "radius", {
  13356. /**
  13357. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13358. */
  13359. get: function () {
  13360. return this._radius;
  13361. },
  13362. /**
  13363. * sets the light radius used by PBR Materials to simulate soft area lights.
  13364. */
  13365. set: function (value) {
  13366. this._radius = value;
  13367. this._computePhotometricScale();
  13368. },
  13369. enumerable: true,
  13370. configurable: true
  13371. });
  13372. ;
  13373. ;
  13374. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13375. get: function () {
  13376. return this._includedOnlyMeshes;
  13377. },
  13378. set: function (value) {
  13379. this._includedOnlyMeshes = value;
  13380. this._hookArrayForIncludedOnly(value);
  13381. },
  13382. enumerable: true,
  13383. configurable: true
  13384. });
  13385. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13386. get: function () {
  13387. return this._excludedMeshes;
  13388. },
  13389. set: function (value) {
  13390. this._excludedMeshes = value;
  13391. this._hookArrayForExcluded(value);
  13392. },
  13393. enumerable: true,
  13394. configurable: true
  13395. });
  13396. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13397. get: function () {
  13398. return this._excludeWithLayerMask;
  13399. },
  13400. set: function (value) {
  13401. this._excludeWithLayerMask = value;
  13402. this._resyncMeshes();
  13403. },
  13404. enumerable: true,
  13405. configurable: true
  13406. });
  13407. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13408. get: function () {
  13409. return this._includeOnlyWithLayerMask;
  13410. },
  13411. set: function (value) {
  13412. this._includeOnlyWithLayerMask = value;
  13413. this._resyncMeshes();
  13414. },
  13415. enumerable: true,
  13416. configurable: true
  13417. });
  13418. Object.defineProperty(Light.prototype, "lightmapMode", {
  13419. get: function () {
  13420. return this._lightmapMode;
  13421. },
  13422. set: function (value) {
  13423. if (this._lightmapMode === value) {
  13424. return;
  13425. }
  13426. this._lightmapMode = value;
  13427. this._markMeshesAsLightDirty();
  13428. },
  13429. enumerable: true,
  13430. configurable: true
  13431. });
  13432. Light.prototype._buildUniformLayout = function () {
  13433. // Overridden
  13434. };
  13435. /**
  13436. * Returns the string "Light".
  13437. */
  13438. Light.prototype.getClassName = function () {
  13439. return "Light";
  13440. };
  13441. /**
  13442. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13443. */
  13444. Light.prototype.toString = function (fullDetails) {
  13445. var ret = "Name: " + this.name;
  13446. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13447. if (this.animations) {
  13448. for (var i = 0; i < this.animations.length; i++) {
  13449. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13450. }
  13451. }
  13452. if (fullDetails) {
  13453. }
  13454. return ret;
  13455. };
  13456. /**
  13457. * Set the enabled state of this node.
  13458. * @param {boolean} value - the new enabled state
  13459. * @see isEnabled
  13460. */
  13461. Light.prototype.setEnabled = function (value) {
  13462. _super.prototype.setEnabled.call(this, value);
  13463. this._resyncMeshes();
  13464. };
  13465. /**
  13466. * Returns the Light associated shadow generator.
  13467. */
  13468. Light.prototype.getShadowGenerator = function () {
  13469. return this._shadowGenerator;
  13470. };
  13471. /**
  13472. * Returns a Vector3, the absolute light position in the World.
  13473. */
  13474. Light.prototype.getAbsolutePosition = function () {
  13475. return BABYLON.Vector3.Zero();
  13476. };
  13477. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13478. };
  13479. Light.prototype._getWorldMatrix = function () {
  13480. return BABYLON.Matrix.Identity();
  13481. };
  13482. /**
  13483. * Boolean : True if the light will affect the passed mesh.
  13484. */
  13485. Light.prototype.canAffectMesh = function (mesh) {
  13486. if (!mesh) {
  13487. return true;
  13488. }
  13489. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13490. return false;
  13491. }
  13492. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13493. return false;
  13494. }
  13495. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13496. return false;
  13497. }
  13498. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13499. return false;
  13500. }
  13501. return true;
  13502. };
  13503. /**
  13504. * Returns the light World matrix.
  13505. */
  13506. Light.prototype.getWorldMatrix = function () {
  13507. this._currentRenderId = this.getScene().getRenderId();
  13508. var worldMatrix = this._getWorldMatrix();
  13509. if (this.parent && this.parent.getWorldMatrix) {
  13510. if (!this._parentedWorldMatrix) {
  13511. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13512. }
  13513. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13514. this._markSyncedWithParent();
  13515. return this._parentedWorldMatrix;
  13516. }
  13517. return worldMatrix;
  13518. };
  13519. /**
  13520. * Sort function to order lights for rendering.
  13521. * @param a First Light object to compare to second.
  13522. * @param b Second Light object to compare first.
  13523. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13524. */
  13525. Light.compareLightsPriority = function (a, b) {
  13526. //shadow-casting lights have priority over non-shadow-casting lights
  13527. //the renderPrioirty is a secondary sort criterion
  13528. if (a.shadowEnabled !== b.shadowEnabled) {
  13529. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13530. }
  13531. return b.renderPriority - a.renderPriority;
  13532. };
  13533. /**
  13534. * Disposes the light.
  13535. */
  13536. Light.prototype.dispose = function () {
  13537. if (this._shadowGenerator) {
  13538. this._shadowGenerator.dispose();
  13539. this._shadowGenerator = null;
  13540. }
  13541. // Animations
  13542. this.getScene().stopAnimation(this);
  13543. // Remove from meshes
  13544. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13545. var mesh = _a[_i];
  13546. mesh._removeLightSource(this);
  13547. }
  13548. this._uniformBuffer.dispose();
  13549. // Remove from scene
  13550. this.getScene().removeLight(this);
  13551. _super.prototype.dispose.call(this);
  13552. };
  13553. /**
  13554. * Returns the light type ID (integer).
  13555. */
  13556. Light.prototype.getTypeID = function () {
  13557. return 0;
  13558. };
  13559. /**
  13560. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13561. */
  13562. Light.prototype.getScaledIntensity = function () {
  13563. return this._photometricScale * this.intensity;
  13564. };
  13565. /**
  13566. * Returns a new Light object, named "name", from the current one.
  13567. */
  13568. Light.prototype.clone = function (name) {
  13569. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13570. };
  13571. /**
  13572. * Serializes the current light into a Serialization object.
  13573. * Returns the serialized object.
  13574. */
  13575. Light.prototype.serialize = function () {
  13576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13577. // Type
  13578. serializationObject.type = this.getTypeID();
  13579. // Parent
  13580. if (this.parent) {
  13581. serializationObject.parentId = this.parent.id;
  13582. }
  13583. // Inclusion / exclusions
  13584. if (this.excludedMeshes.length > 0) {
  13585. serializationObject.excludedMeshesIds = [];
  13586. this.excludedMeshes.forEach(function (mesh) {
  13587. serializationObject.excludedMeshesIds.push(mesh.id);
  13588. });
  13589. }
  13590. if (this.includedOnlyMeshes.length > 0) {
  13591. serializationObject.includedOnlyMeshesIds = [];
  13592. this.includedOnlyMeshes.forEach(function (mesh) {
  13593. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13594. });
  13595. }
  13596. // Animations
  13597. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13598. serializationObject.ranges = this.serializeAnimationRanges();
  13599. return serializationObject;
  13600. };
  13601. /**
  13602. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13603. * This new light is named "name" and added to the passed scene.
  13604. */
  13605. Light.GetConstructorFromName = function (type, name, scene) {
  13606. switch (type) {
  13607. case 0:
  13608. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13609. case 1:
  13610. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13611. case 2:
  13612. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13613. case 3:
  13614. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13615. }
  13616. };
  13617. /**
  13618. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13619. */
  13620. Light.Parse = function (parsedLight, scene) {
  13621. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13622. // Inclusion / exclusions
  13623. if (parsedLight.excludedMeshesIds) {
  13624. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13625. }
  13626. if (parsedLight.includedOnlyMeshesIds) {
  13627. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13628. }
  13629. // Parent
  13630. if (parsedLight.parentId) {
  13631. light._waitingParentId = parsedLight.parentId;
  13632. }
  13633. // Animations
  13634. if (parsedLight.animations) {
  13635. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13636. var parsedAnimation = parsedLight.animations[animationIndex];
  13637. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13638. }
  13639. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13640. }
  13641. if (parsedLight.autoAnimate) {
  13642. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13643. }
  13644. return light;
  13645. };
  13646. Light.prototype._hookArrayForExcluded = function (array) {
  13647. var _this = this;
  13648. var oldPush = array.push;
  13649. array.push = function () {
  13650. var items = [];
  13651. for (var _i = 0; _i < arguments.length; _i++) {
  13652. items[_i] = arguments[_i];
  13653. }
  13654. var result = oldPush.apply(array, items);
  13655. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13656. var item = items_1[_a];
  13657. item._resyncLighSource(_this);
  13658. }
  13659. return result;
  13660. };
  13661. var oldSplice = array.splice;
  13662. array.splice = function (index, deleteCount) {
  13663. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13664. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13665. var item = deleted_1[_i];
  13666. item._resyncLighSource(_this);
  13667. }
  13668. return deleted;
  13669. };
  13670. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13671. var item = array_1[_i];
  13672. item._resyncLighSource(this);
  13673. }
  13674. };
  13675. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13676. var _this = this;
  13677. var oldPush = array.push;
  13678. array.push = function () {
  13679. var items = [];
  13680. for (var _i = 0; _i < arguments.length; _i++) {
  13681. items[_i] = arguments[_i];
  13682. }
  13683. var result = oldPush.apply(array, items);
  13684. _this._resyncMeshes();
  13685. return result;
  13686. };
  13687. var oldSplice = array.splice;
  13688. array.splice = function (index, deleteCount) {
  13689. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13690. _this._resyncMeshes();
  13691. return deleted;
  13692. };
  13693. this._resyncMeshes();
  13694. };
  13695. Light.prototype._resyncMeshes = function () {
  13696. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13697. var mesh = _a[_i];
  13698. mesh._resyncLighSource(this);
  13699. }
  13700. };
  13701. Light.prototype._markMeshesAsLightDirty = function () {
  13702. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13703. var mesh = _a[_i];
  13704. if (mesh._lightSources.indexOf(this) !== -1) {
  13705. mesh._markSubMeshesAsLightDirty();
  13706. }
  13707. }
  13708. };
  13709. /**
  13710. * Recomputes the cached photometric scale if needed.
  13711. */
  13712. Light.prototype._computePhotometricScale = function () {
  13713. this._photometricScale = this._getPhotometricScale();
  13714. this.getScene().resetCachedMaterial();
  13715. };
  13716. /**
  13717. * Returns the Photometric Scale according to the light type and intensity mode.
  13718. */
  13719. Light.prototype._getPhotometricScale = function () {
  13720. var photometricScale = 0.0;
  13721. var lightTypeID = this.getTypeID();
  13722. //get photometric mode
  13723. var photometricMode = this.intensityMode;
  13724. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13725. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13726. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13727. }
  13728. else {
  13729. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13730. }
  13731. }
  13732. //compute photometric scale
  13733. switch (lightTypeID) {
  13734. case Light.LIGHTTYPEID_POINTLIGHT:
  13735. case Light.LIGHTTYPEID_SPOTLIGHT:
  13736. switch (photometricMode) {
  13737. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13738. photometricScale = 1.0 / (4.0 * Math.PI);
  13739. break;
  13740. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13741. photometricScale = 1.0;
  13742. break;
  13743. case Light.INTENSITYMODE_LUMINANCE:
  13744. photometricScale = this.radius * this.radius;
  13745. break;
  13746. }
  13747. break;
  13748. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13749. switch (photometricMode) {
  13750. case Light.INTENSITYMODE_ILLUMINANCE:
  13751. photometricScale = 1.0;
  13752. break;
  13753. case Light.INTENSITYMODE_LUMINANCE:
  13754. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13755. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13756. var apexAngleRadians = this.radius;
  13757. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13758. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13759. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13760. photometricScale = solidAngle;
  13761. break;
  13762. }
  13763. break;
  13764. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13765. // No fall off in hemisperic light.
  13766. photometricScale = 1.0;
  13767. break;
  13768. }
  13769. return photometricScale;
  13770. };
  13771. Light.prototype._reorderLightsInScene = function () {
  13772. var scene = this.getScene();
  13773. if (this.renderPriority != 0) {
  13774. scene.requireLightSorting = true;
  13775. }
  13776. this.getScene().sortLightsByPriority();
  13777. };
  13778. return Light;
  13779. }(BABYLON.Node));
  13780. //lightmapMode Consts
  13781. Light._LIGHTMAP_DEFAULT = 0;
  13782. Light._LIGHTMAP_SPECULAR = 1;
  13783. Light._LIGHTMAP_SHADOWSONLY = 2;
  13784. // Intensity Mode Consts
  13785. Light._INTENSITYMODE_AUTOMATIC = 0;
  13786. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13787. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13788. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13789. Light._INTENSITYMODE_LUMINANCE = 4;
  13790. // Light types ids const.
  13791. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13792. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13793. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13794. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13795. __decorate([
  13796. BABYLON.serializeAsColor3()
  13797. ], Light.prototype, "diffuse", void 0);
  13798. __decorate([
  13799. BABYLON.serializeAsColor3()
  13800. ], Light.prototype, "specular", void 0);
  13801. __decorate([
  13802. BABYLON.serialize()
  13803. ], Light.prototype, "intensity", void 0);
  13804. __decorate([
  13805. BABYLON.serialize()
  13806. ], Light.prototype, "range", void 0);
  13807. __decorate([
  13808. BABYLON.serialize()
  13809. ], Light.prototype, "intensityMode", null);
  13810. __decorate([
  13811. BABYLON.serialize()
  13812. ], Light.prototype, "radius", null);
  13813. __decorate([
  13814. BABYLON.serialize()
  13815. ], Light.prototype, "_renderPriority", void 0);
  13816. __decorate([
  13817. BABYLON.expandToProperty("_reorderLightsInScene")
  13818. ], Light.prototype, "renderPriority", void 0);
  13819. __decorate([
  13820. BABYLON.serialize()
  13821. ], Light.prototype, "shadowEnabled", void 0);
  13822. __decorate([
  13823. BABYLON.serialize("excludeWithLayerMask")
  13824. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13825. __decorate([
  13826. BABYLON.serialize("includeOnlyWithLayerMask")
  13827. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13828. __decorate([
  13829. BABYLON.serialize("lightmapMode")
  13830. ], Light.prototype, "_lightmapMode", void 0);
  13831. BABYLON.Light = Light;
  13832. })(BABYLON || (BABYLON = {}));
  13833. //# sourceMappingURL=babylon.light.js.map
  13834. var BABYLON;
  13835. (function (BABYLON) {
  13836. var Camera = (function (_super) {
  13837. __extends(Camera, _super);
  13838. function Camera(name, position, scene) {
  13839. var _this = _super.call(this, name, scene) || this;
  13840. _this.upVector = BABYLON.Vector3.Up();
  13841. _this.orthoLeft = null;
  13842. _this.orthoRight = null;
  13843. _this.orthoBottom = null;
  13844. _this.orthoTop = null;
  13845. _this.fov = 0.8;
  13846. _this.minZ = 1.0;
  13847. _this.maxZ = 10000.0;
  13848. _this.inertia = 0.9;
  13849. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13850. _this.isIntermediate = false;
  13851. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13852. _this.layerMask = 0x0FFFFFFF;
  13853. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13854. // Camera rig members
  13855. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13856. _this._rigCameras = new Array();
  13857. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13858. // Cache
  13859. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13860. _this._projectionMatrix = new BABYLON.Matrix();
  13861. _this._doNotComputeProjectionMatrix = false;
  13862. _this._postProcesses = new Array();
  13863. _this._transformMatrix = BABYLON.Matrix.Zero();
  13864. _this._activeMeshes = new BABYLON.SmartArray(256);
  13865. _this._globalPosition = BABYLON.Vector3.Zero();
  13866. _this._refreshFrustumPlanes = true;
  13867. _this.getScene().addCamera(_this);
  13868. if (!_this.getScene().activeCamera) {
  13869. _this.getScene().activeCamera = _this;
  13870. }
  13871. _this.position = position;
  13872. return _this;
  13873. }
  13874. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13875. get: function () {
  13876. return Camera._PERSPECTIVE_CAMERA;
  13877. },
  13878. enumerable: true,
  13879. configurable: true
  13880. });
  13881. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13882. get: function () {
  13883. return Camera._ORTHOGRAPHIC_CAMERA;
  13884. },
  13885. enumerable: true,
  13886. configurable: true
  13887. });
  13888. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13889. get: function () {
  13890. return Camera._FOVMODE_VERTICAL_FIXED;
  13891. },
  13892. enumerable: true,
  13893. configurable: true
  13894. });
  13895. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13896. get: function () {
  13897. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13898. },
  13899. enumerable: true,
  13900. configurable: true
  13901. });
  13902. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13903. get: function () {
  13904. return Camera._RIG_MODE_NONE;
  13905. },
  13906. enumerable: true,
  13907. configurable: true
  13908. });
  13909. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13910. get: function () {
  13911. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13912. },
  13913. enumerable: true,
  13914. configurable: true
  13915. });
  13916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13917. get: function () {
  13918. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13919. },
  13920. enumerable: true,
  13921. configurable: true
  13922. });
  13923. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13924. get: function () {
  13925. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13926. },
  13927. enumerable: true,
  13928. configurable: true
  13929. });
  13930. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13931. get: function () {
  13932. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13933. },
  13934. enumerable: true,
  13935. configurable: true
  13936. });
  13937. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13938. get: function () {
  13939. return Camera._RIG_MODE_VR;
  13940. },
  13941. enumerable: true,
  13942. configurable: true
  13943. });
  13944. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13945. get: function () {
  13946. return Camera._RIG_MODE_WEBVR;
  13947. },
  13948. enumerable: true,
  13949. configurable: true
  13950. });
  13951. Camera.prototype.getClassName = function () {
  13952. return "Camera";
  13953. };
  13954. /**
  13955. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13956. */
  13957. Camera.prototype.toString = function (fullDetails) {
  13958. var ret = "Name: " + this.name;
  13959. ret += ", type: " + this.getClassName();
  13960. if (this.animations) {
  13961. for (var i = 0; i < this.animations.length; i++) {
  13962. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13963. }
  13964. }
  13965. if (fullDetails) {
  13966. }
  13967. return ret;
  13968. };
  13969. Object.defineProperty(Camera.prototype, "globalPosition", {
  13970. get: function () {
  13971. return this._globalPosition;
  13972. },
  13973. enumerable: true,
  13974. configurable: true
  13975. });
  13976. Camera.prototype.getActiveMeshes = function () {
  13977. return this._activeMeshes;
  13978. };
  13979. Camera.prototype.isActiveMesh = function (mesh) {
  13980. return (this._activeMeshes.indexOf(mesh) !== -1);
  13981. };
  13982. //Cache
  13983. Camera.prototype._initCache = function () {
  13984. _super.prototype._initCache.call(this);
  13985. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13986. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13987. this._cache.mode = undefined;
  13988. this._cache.minZ = undefined;
  13989. this._cache.maxZ = undefined;
  13990. this._cache.fov = undefined;
  13991. this._cache.fovMode = undefined;
  13992. this._cache.aspectRatio = undefined;
  13993. this._cache.orthoLeft = undefined;
  13994. this._cache.orthoRight = undefined;
  13995. this._cache.orthoBottom = undefined;
  13996. this._cache.orthoTop = undefined;
  13997. this._cache.renderWidth = undefined;
  13998. this._cache.renderHeight = undefined;
  13999. };
  14000. Camera.prototype._updateCache = function (ignoreParentClass) {
  14001. if (!ignoreParentClass) {
  14002. _super.prototype._updateCache.call(this);
  14003. }
  14004. var engine = this.getEngine();
  14005. this._cache.position.copyFrom(this.position);
  14006. this._cache.upVector.copyFrom(this.upVector);
  14007. this._cache.mode = this.mode;
  14008. this._cache.minZ = this.minZ;
  14009. this._cache.maxZ = this.maxZ;
  14010. this._cache.fov = this.fov;
  14011. this._cache.fovMode = this.fovMode;
  14012. this._cache.aspectRatio = engine.getAspectRatio(this);
  14013. this._cache.orthoLeft = this.orthoLeft;
  14014. this._cache.orthoRight = this.orthoRight;
  14015. this._cache.orthoBottom = this.orthoBottom;
  14016. this._cache.orthoTop = this.orthoTop;
  14017. this._cache.renderWidth = engine.getRenderWidth();
  14018. this._cache.renderHeight = engine.getRenderHeight();
  14019. };
  14020. Camera.prototype._updateFromScene = function () {
  14021. this.updateCache();
  14022. this.update();
  14023. };
  14024. // Synchronized
  14025. Camera.prototype._isSynchronized = function () {
  14026. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14027. };
  14028. Camera.prototype._isSynchronizedViewMatrix = function () {
  14029. if (!_super.prototype._isSynchronized.call(this))
  14030. return false;
  14031. return this._cache.position.equals(this.position)
  14032. && this._cache.upVector.equals(this.upVector)
  14033. && this.isSynchronizedWithParent();
  14034. };
  14035. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14036. var check = this._cache.mode === this.mode
  14037. && this._cache.minZ === this.minZ
  14038. && this._cache.maxZ === this.maxZ;
  14039. if (!check) {
  14040. return false;
  14041. }
  14042. var engine = this.getEngine();
  14043. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14044. check = this._cache.fov === this.fov
  14045. && this._cache.fovMode === this.fovMode
  14046. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14047. }
  14048. else {
  14049. check = this._cache.orthoLeft === this.orthoLeft
  14050. && this._cache.orthoRight === this.orthoRight
  14051. && this._cache.orthoBottom === this.orthoBottom
  14052. && this._cache.orthoTop === this.orthoTop
  14053. && this._cache.renderWidth === engine.getRenderWidth()
  14054. && this._cache.renderHeight === engine.getRenderHeight();
  14055. }
  14056. return check;
  14057. };
  14058. // Controls
  14059. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14060. };
  14061. Camera.prototype.detachControl = function (element) {
  14062. };
  14063. Camera.prototype.update = function () {
  14064. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14065. this._updateRigCameras();
  14066. }
  14067. this._checkInputs();
  14068. };
  14069. Camera.prototype._checkInputs = function () {
  14070. };
  14071. Object.defineProperty(Camera.prototype, "rigCameras", {
  14072. get: function () {
  14073. return this._rigCameras;
  14074. },
  14075. enumerable: true,
  14076. configurable: true
  14077. });
  14078. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14079. get: function () {
  14080. return this._rigPostProcess;
  14081. },
  14082. enumerable: true,
  14083. configurable: true
  14084. });
  14085. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14086. // invalidate framebuffer
  14087. if (this._postProcesses.length > 0) {
  14088. this._postProcesses[0].markTextureDirty();
  14089. }
  14090. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14091. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14092. var cam = this._rigCameras[i];
  14093. var rigPostProcess = cam._rigPostProcess;
  14094. // for VR rig, there does not have to be a post process
  14095. if (rigPostProcess) {
  14096. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14097. if (isPass) {
  14098. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14099. cam.isIntermediate = this._postProcesses.length === 0;
  14100. }
  14101. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14102. rigPostProcess.markTextureDirty();
  14103. }
  14104. else {
  14105. cam._postProcesses = this._postProcesses.slice(0);
  14106. }
  14107. }
  14108. };
  14109. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14110. if (insertAt === void 0) { insertAt = null; }
  14111. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14112. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14113. return 0;
  14114. }
  14115. if (insertAt == null || insertAt < 0) {
  14116. this._postProcesses.push(postProcess);
  14117. }
  14118. else {
  14119. this._postProcesses.splice(insertAt, 0, postProcess);
  14120. }
  14121. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14122. return this._postProcesses.indexOf(postProcess);
  14123. };
  14124. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14125. if (atIndices === void 0) { atIndices = null; }
  14126. var result = [];
  14127. var i;
  14128. var index;
  14129. if (!atIndices) {
  14130. var idx = this._postProcesses.indexOf(postProcess);
  14131. if (idx !== -1) {
  14132. this._postProcesses.splice(idx, 1);
  14133. }
  14134. }
  14135. else {
  14136. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14137. // iterate descending, so can just splice as we go
  14138. for (i = atIndices.length - 1; i >= 0; i--) {
  14139. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14140. result.push(i);
  14141. continue;
  14142. }
  14143. index = atIndices[i];
  14144. this._postProcesses.splice(index, 1);
  14145. }
  14146. }
  14147. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14148. return result;
  14149. };
  14150. Camera.prototype.getWorldMatrix = function () {
  14151. if (!this._worldMatrix) {
  14152. this._worldMatrix = BABYLON.Matrix.Identity();
  14153. }
  14154. var viewMatrix = this.getViewMatrix();
  14155. viewMatrix.invertToRef(this._worldMatrix);
  14156. return this._worldMatrix;
  14157. };
  14158. Camera.prototype._getViewMatrix = function () {
  14159. return BABYLON.Matrix.Identity();
  14160. };
  14161. Camera.prototype.getViewMatrix = function (force) {
  14162. this._computedViewMatrix = this._computeViewMatrix(force);
  14163. if (!force && this._isSynchronizedViewMatrix()) {
  14164. return this._computedViewMatrix;
  14165. }
  14166. this._refreshFrustumPlanes = true;
  14167. if (!this.parent || !this.parent.getWorldMatrix) {
  14168. this._globalPosition.copyFrom(this.position);
  14169. }
  14170. else {
  14171. if (!this._worldMatrix) {
  14172. this._worldMatrix = BABYLON.Matrix.Identity();
  14173. }
  14174. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14175. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14176. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14177. this._computedViewMatrix.invert();
  14178. this._markSyncedWithParent();
  14179. }
  14180. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14181. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14182. }
  14183. this._currentRenderId = this.getScene().getRenderId();
  14184. return this._computedViewMatrix;
  14185. };
  14186. Camera.prototype._computeViewMatrix = function (force) {
  14187. if (!force && this._isSynchronizedViewMatrix()) {
  14188. return this._computedViewMatrix;
  14189. }
  14190. this._computedViewMatrix = this._getViewMatrix();
  14191. this._currentRenderId = this.getScene().getRenderId();
  14192. return this._computedViewMatrix;
  14193. };
  14194. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14195. this._doNotComputeProjectionMatrix = true;
  14196. if (projection !== undefined) {
  14197. this._projectionMatrix = projection;
  14198. }
  14199. };
  14200. ;
  14201. Camera.prototype.unfreezeProjectionMatrix = function () {
  14202. this._doNotComputeProjectionMatrix = false;
  14203. };
  14204. ;
  14205. Camera.prototype.getProjectionMatrix = function (force) {
  14206. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14207. return this._projectionMatrix;
  14208. }
  14209. this._refreshFrustumPlanes = true;
  14210. var engine = this.getEngine();
  14211. var scene = this.getScene();
  14212. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14213. if (this.minZ <= 0) {
  14214. this.minZ = 0.1;
  14215. }
  14216. if (scene.useRightHandedSystem) {
  14217. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14218. }
  14219. else {
  14220. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14221. }
  14222. return this._projectionMatrix;
  14223. }
  14224. var halfWidth = engine.getRenderWidth() / 2.0;
  14225. var halfHeight = engine.getRenderHeight() / 2.0;
  14226. if (scene.useRightHandedSystem) {
  14227. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14228. }
  14229. else {
  14230. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14231. }
  14232. return this._projectionMatrix;
  14233. };
  14234. Camera.prototype.getTranformationMatrix = function () {
  14235. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14236. return this._transformMatrix;
  14237. };
  14238. Camera.prototype.updateFrustumPlanes = function () {
  14239. if (!this._refreshFrustumPlanes) {
  14240. return;
  14241. }
  14242. this.getTranformationMatrix();
  14243. if (!this._frustumPlanes) {
  14244. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14245. }
  14246. else {
  14247. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14248. }
  14249. this._refreshFrustumPlanes = false;
  14250. };
  14251. Camera.prototype.isInFrustum = function (target) {
  14252. this.updateFrustumPlanes();
  14253. return target.isInFrustum(this._frustumPlanes);
  14254. };
  14255. Camera.prototype.isCompletelyInFrustum = function (target) {
  14256. this.updateFrustumPlanes();
  14257. return target.isCompletelyInFrustum(this._frustumPlanes);
  14258. };
  14259. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14260. if (length === void 0) { length = 100; }
  14261. if (!transform) {
  14262. transform = this.getWorldMatrix();
  14263. }
  14264. if (!origin) {
  14265. origin = this.position;
  14266. }
  14267. var forward = new BABYLON.Vector3(0, 0, 1);
  14268. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14269. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14270. return new BABYLON.Ray(origin, direction, length);
  14271. };
  14272. Camera.prototype.dispose = function () {
  14273. // Animations
  14274. this.getScene().stopAnimation(this);
  14275. // Remove from scene
  14276. this.getScene().removeCamera(this);
  14277. while (this._rigCameras.length > 0) {
  14278. this._rigCameras.pop().dispose();
  14279. }
  14280. // Postprocesses
  14281. var i = this._postProcesses.length;
  14282. while (--i >= 0) {
  14283. this._postProcesses[i].dispose(this);
  14284. }
  14285. _super.prototype.dispose.call(this);
  14286. };
  14287. Object.defineProperty(Camera.prototype, "leftCamera", {
  14288. // ---- Camera rigs section ----
  14289. get: function () {
  14290. if (this._rigCameras.length < 1) {
  14291. return undefined;
  14292. }
  14293. return this._rigCameras[0];
  14294. },
  14295. enumerable: true,
  14296. configurable: true
  14297. });
  14298. Object.defineProperty(Camera.prototype, "rightCamera", {
  14299. get: function () {
  14300. if (this._rigCameras.length < 2) {
  14301. return undefined;
  14302. }
  14303. return this._rigCameras[1];
  14304. },
  14305. enumerable: true,
  14306. configurable: true
  14307. });
  14308. Camera.prototype.getLeftTarget = function () {
  14309. if (this._rigCameras.length < 1) {
  14310. return undefined;
  14311. }
  14312. return this._rigCameras[0].getTarget();
  14313. };
  14314. Camera.prototype.getRightTarget = function () {
  14315. if (this._rigCameras.length < 2) {
  14316. return undefined;
  14317. }
  14318. return this._rigCameras[1].getTarget();
  14319. };
  14320. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14321. while (this._rigCameras.length > 0) {
  14322. this._rigCameras.pop().dispose();
  14323. }
  14324. this.cameraRigMode = mode;
  14325. this._cameraRigParams = {};
  14326. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14327. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14328. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14329. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14330. // create the rig cameras, unless none
  14331. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14332. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14333. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14334. }
  14335. switch (this.cameraRigMode) {
  14336. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14337. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14338. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14339. break;
  14340. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14341. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14342. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14343. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14344. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14345. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14346. break;
  14347. case Camera.RIG_MODE_VR:
  14348. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14349. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14350. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14351. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14352. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14353. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14354. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14355. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14356. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14357. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14358. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14359. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14360. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14361. if (metrics.compensateDistortion) {
  14362. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14363. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14364. }
  14365. break;
  14366. case Camera.RIG_MODE_WEBVR:
  14367. if (rigParams.vrDisplay) {
  14368. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14369. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14370. //Left eye
  14371. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14372. this._rigCameras[0].setCameraRigParameter("left", true);
  14373. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14374. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14375. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14376. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14377. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14378. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14379. this._rigCameras[0].parent = this;
  14380. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14381. //Right eye
  14382. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14383. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14384. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14385. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14386. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14387. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14388. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14389. this._rigCameras[1].parent = this;
  14390. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14391. }
  14392. break;
  14393. }
  14394. this._cascadePostProcessesToRigCams();
  14395. this.
  14396. update();
  14397. };
  14398. Camera.prototype._getVRProjectionMatrix = function () {
  14399. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14400. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14401. return this._projectionMatrix;
  14402. };
  14403. Camera.prototype._updateCameraRotationMatrix = function () {
  14404. //Here for WebVR
  14405. };
  14406. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14407. //Here for WebVR
  14408. };
  14409. /**
  14410. * This function MUST be overwritten by the different WebVR cameras available.
  14411. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14412. */
  14413. Camera.prototype._getWebVRProjectionMatrix = function () {
  14414. return BABYLON.Matrix.Identity();
  14415. };
  14416. /**
  14417. * This function MUST be overwritten by the different WebVR cameras available.
  14418. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14419. */
  14420. Camera.prototype._getWebVRViewMatrix = function () {
  14421. return BABYLON.Matrix.Identity();
  14422. };
  14423. Camera.prototype.setCameraRigParameter = function (name, value) {
  14424. if (!this._cameraRigParams) {
  14425. this._cameraRigParams = {};
  14426. }
  14427. this._cameraRigParams[name] = value;
  14428. //provisionnally:
  14429. if (name === "interaxialDistance") {
  14430. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14431. }
  14432. };
  14433. /**
  14434. * needs to be overridden by children so sub has required properties to be copied
  14435. */
  14436. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14437. return null;
  14438. };
  14439. /**
  14440. * May need to be overridden by children
  14441. */
  14442. Camera.prototype._updateRigCameras = function () {
  14443. for (var i = 0; i < this._rigCameras.length; i++) {
  14444. this._rigCameras[i].minZ = this.minZ;
  14445. this._rigCameras[i].maxZ = this.maxZ;
  14446. this._rigCameras[i].fov = this.fov;
  14447. }
  14448. // only update viewport when ANAGLYPH
  14449. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14450. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14451. }
  14452. };
  14453. Camera.prototype._setupInputs = function () {
  14454. };
  14455. Camera.prototype.serialize = function () {
  14456. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14457. // Type
  14458. serializationObject.type = this.getClassName();
  14459. // Parent
  14460. if (this.parent) {
  14461. serializationObject.parentId = this.parent.id;
  14462. }
  14463. if (this.inputs) {
  14464. this.inputs.serialize(serializationObject);
  14465. }
  14466. // Animations
  14467. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14468. serializationObject.ranges = this.serializeAnimationRanges();
  14469. return serializationObject;
  14470. };
  14471. Camera.prototype.clone = function (name) {
  14472. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14473. };
  14474. Camera.prototype.getDirection = function (localAxis) {
  14475. var result = BABYLON.Vector3.Zero();
  14476. this.getDirectionToRef(localAxis, result);
  14477. return result;
  14478. };
  14479. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14480. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14481. };
  14482. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14483. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14484. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14485. switch (type) {
  14486. case "ArcRotateCamera":
  14487. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14488. case "DeviceOrientationCamera":
  14489. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14490. case "FollowCamera":
  14491. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14492. case "ArcFollowCamera":
  14493. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14494. case "GamepadCamera":
  14495. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14496. case "TouchCamera":
  14497. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14498. case "VirtualJoysticksCamera":
  14499. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14500. case "WebVRFreeCamera":
  14501. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14502. case "WebVRGamepadCamera":
  14503. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14504. case "VRDeviceOrientationFreeCamera":
  14505. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14506. case "VRDeviceOrientationGamepadCamera":
  14507. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14508. case "AnaglyphArcRotateCamera":
  14509. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14510. case "AnaglyphFreeCamera":
  14511. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14512. case "AnaglyphGamepadCamera":
  14513. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14514. case "AnaglyphUniversalCamera":
  14515. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14516. case "StereoscopicArcRotateCamera":
  14517. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14518. case "StereoscopicFreeCamera":
  14519. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14520. case "StereoscopicGamepadCamera":
  14521. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14522. case "StereoscopicUniversalCamera":
  14523. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14524. case "FreeCamera":
  14525. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14526. default:
  14527. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14528. }
  14529. };
  14530. Camera.Parse = function (parsedCamera, scene) {
  14531. var type = parsedCamera.type;
  14532. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14533. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14534. // Parent
  14535. if (parsedCamera.parentId) {
  14536. camera._waitingParentId = parsedCamera.parentId;
  14537. }
  14538. //If camera has an input manager, let it parse inputs settings
  14539. if (camera.inputs) {
  14540. camera.inputs.parse(parsedCamera);
  14541. camera._setupInputs();
  14542. }
  14543. // Target
  14544. if (parsedCamera.target) {
  14545. if (camera.setTarget) {
  14546. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14547. }
  14548. }
  14549. // Apply 3d rig, when found
  14550. if (parsedCamera.cameraRigMode) {
  14551. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14552. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14553. }
  14554. // Animations
  14555. if (parsedCamera.animations) {
  14556. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14557. var parsedAnimation = parsedCamera.animations[animationIndex];
  14558. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14559. }
  14560. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14561. }
  14562. if (parsedCamera.autoAnimate) {
  14563. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14564. }
  14565. return camera;
  14566. };
  14567. return Camera;
  14568. }(BABYLON.Node));
  14569. // Statics
  14570. Camera._PERSPECTIVE_CAMERA = 0;
  14571. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14572. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14573. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14574. Camera._RIG_MODE_NONE = 0;
  14575. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14576. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14577. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14578. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14579. Camera._RIG_MODE_VR = 20;
  14580. Camera._RIG_MODE_WEBVR = 21;
  14581. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14582. __decorate([
  14583. BABYLON.serializeAsVector3()
  14584. ], Camera.prototype, "position", void 0);
  14585. __decorate([
  14586. BABYLON.serializeAsVector3()
  14587. ], Camera.prototype, "upVector", void 0);
  14588. __decorate([
  14589. BABYLON.serialize()
  14590. ], Camera.prototype, "orthoLeft", void 0);
  14591. __decorate([
  14592. BABYLON.serialize()
  14593. ], Camera.prototype, "orthoRight", void 0);
  14594. __decorate([
  14595. BABYLON.serialize()
  14596. ], Camera.prototype, "orthoBottom", void 0);
  14597. __decorate([
  14598. BABYLON.serialize()
  14599. ], Camera.prototype, "orthoTop", void 0);
  14600. __decorate([
  14601. BABYLON.serialize()
  14602. ], Camera.prototype, "fov", void 0);
  14603. __decorate([
  14604. BABYLON.serialize()
  14605. ], Camera.prototype, "minZ", void 0);
  14606. __decorate([
  14607. BABYLON.serialize()
  14608. ], Camera.prototype, "maxZ", void 0);
  14609. __decorate([
  14610. BABYLON.serialize()
  14611. ], Camera.prototype, "inertia", void 0);
  14612. __decorate([
  14613. BABYLON.serialize()
  14614. ], Camera.prototype, "mode", void 0);
  14615. __decorate([
  14616. BABYLON.serialize()
  14617. ], Camera.prototype, "layerMask", void 0);
  14618. __decorate([
  14619. BABYLON.serialize()
  14620. ], Camera.prototype, "fovMode", void 0);
  14621. __decorate([
  14622. BABYLON.serialize()
  14623. ], Camera.prototype, "cameraRigMode", void 0);
  14624. __decorate([
  14625. BABYLON.serialize()
  14626. ], Camera.prototype, "interaxialDistance", void 0);
  14627. __decorate([
  14628. BABYLON.serialize()
  14629. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14630. BABYLON.Camera = Camera;
  14631. })(BABYLON || (BABYLON = {}));
  14632. //# sourceMappingURL=babylon.camera.js.map
  14633. var BABYLON;
  14634. (function (BABYLON) {
  14635. var RenderingManager = (function () {
  14636. function RenderingManager(scene) {
  14637. this._renderingGroups = new Array();
  14638. this._autoClearDepthStencil = {};
  14639. this._customOpaqueSortCompareFn = {};
  14640. this._customAlphaTestSortCompareFn = {};
  14641. this._customTransparentSortCompareFn = {};
  14642. this._renderinGroupInfo = null;
  14643. this._scene = scene;
  14644. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14645. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14646. }
  14647. }
  14648. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14649. if (depth === void 0) { depth = true; }
  14650. if (stencil === void 0) { stencil = true; }
  14651. if (this._depthStencilBufferAlreadyCleaned) {
  14652. return;
  14653. }
  14654. this._scene.getEngine().clear(null, false, depth, stencil);
  14655. this._depthStencilBufferAlreadyCleaned = true;
  14656. };
  14657. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14658. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14659. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14660. var info = null;
  14661. if (observable) {
  14662. if (!this._renderinGroupInfo) {
  14663. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14664. }
  14665. info = this._renderinGroupInfo;
  14666. info.scene = this._scene;
  14667. info.camera = this._scene.activeCamera;
  14668. }
  14669. // Dispatch sprites
  14670. if (renderSprites) {
  14671. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14672. var manager = this._scene.spriteManagers[index];
  14673. this.dispatchSprites(manager);
  14674. }
  14675. }
  14676. // Render
  14677. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14678. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14679. var renderingGroup = this._renderingGroups[index];
  14680. if (!renderingGroup && !observable)
  14681. continue;
  14682. this._currentIndex = index;
  14683. var renderingGroupMask = 0;
  14684. // Fire PRECLEAR stage
  14685. if (observable) {
  14686. renderingGroupMask = Math.pow(2, index);
  14687. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14688. info.renderingGroupId = index;
  14689. observable.notifyObservers(info, renderingGroupMask);
  14690. }
  14691. // Clear depth/stencil if needed
  14692. if (RenderingManager.AUTOCLEAR) {
  14693. var autoClear = this._autoClearDepthStencil[index];
  14694. if (autoClear && autoClear.autoClear) {
  14695. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14696. }
  14697. }
  14698. if (observable) {
  14699. // Fire PREOPAQUE stage
  14700. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14701. observable.notifyObservers(info, renderingGroupMask);
  14702. // Fire PRETRANSPARENT stage
  14703. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14704. observable.notifyObservers(info, renderingGroupMask);
  14705. }
  14706. if (renderingGroup)
  14707. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14708. // Fire POSTTRANSPARENT stage
  14709. if (observable) {
  14710. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14711. observable.notifyObservers(info, renderingGroupMask);
  14712. }
  14713. }
  14714. };
  14715. RenderingManager.prototype.reset = function () {
  14716. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14717. var renderingGroup = this._renderingGroups[index];
  14718. if (renderingGroup) {
  14719. renderingGroup.prepare();
  14720. }
  14721. }
  14722. };
  14723. RenderingManager.prototype.dispose = function () {
  14724. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14725. var renderingGroup = this._renderingGroups[index];
  14726. if (renderingGroup) {
  14727. renderingGroup.dispose();
  14728. }
  14729. }
  14730. this._renderingGroups.length = 0;
  14731. };
  14732. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14733. if (!this._renderingGroups[renderingGroupId]) {
  14734. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14735. }
  14736. };
  14737. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14738. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14739. this._prepareRenderingGroup(renderingGroupId);
  14740. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14741. };
  14742. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14743. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14744. this._prepareRenderingGroup(renderingGroupId);
  14745. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14746. };
  14747. RenderingManager.prototype.dispatch = function (subMesh) {
  14748. var mesh = subMesh.getMesh();
  14749. var renderingGroupId = mesh.renderingGroupId || 0;
  14750. this._prepareRenderingGroup(renderingGroupId);
  14751. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14752. };
  14753. /**
  14754. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14755. * This allowed control for front to back rendering or reversly depending of the special needs.
  14756. *
  14757. * @param renderingGroupId The rendering group id corresponding to its index
  14758. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14759. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14760. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14761. */
  14762. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14763. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14764. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14765. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14766. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14767. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14768. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14769. if (this._renderingGroups[renderingGroupId]) {
  14770. var group = this._renderingGroups[renderingGroupId];
  14771. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14772. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14773. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14774. }
  14775. };
  14776. /**
  14777. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14778. *
  14779. * @param renderingGroupId The rendering group id corresponding to its index
  14780. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14781. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14782. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14783. */
  14784. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14785. if (depth === void 0) { depth = true; }
  14786. if (stencil === void 0) { stencil = true; }
  14787. this._autoClearDepthStencil[renderingGroupId] = {
  14788. autoClear: autoClearDepthStencil,
  14789. depth: depth,
  14790. stencil: stencil
  14791. };
  14792. };
  14793. return RenderingManager;
  14794. }());
  14795. /**
  14796. * The max id used for rendering groups (not included)
  14797. */
  14798. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14799. /**
  14800. * The min id used for rendering groups (included)
  14801. */
  14802. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14803. /**
  14804. * Used to globally prevent autoclearing scenes.
  14805. */
  14806. RenderingManager.AUTOCLEAR = true;
  14807. BABYLON.RenderingManager = RenderingManager;
  14808. })(BABYLON || (BABYLON = {}));
  14809. //# sourceMappingURL=babylon.renderingManager.js.map
  14810. var BABYLON;
  14811. (function (BABYLON) {
  14812. var RenderingGroup = (function () {
  14813. /**
  14814. * Creates a new rendering group.
  14815. * @param index The rendering group index
  14816. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14817. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14818. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14819. */
  14820. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14821. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14822. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14823. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14824. this.index = index;
  14825. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14826. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14827. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14828. this._particleSystems = new BABYLON.SmartArray(256);
  14829. this._spriteManagers = new BABYLON.SmartArray(256);
  14830. this._edgesRenderers = new BABYLON.SmartArray(16);
  14831. this._scene = scene;
  14832. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14833. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14834. this.transparentSortCompareFn = transparentSortCompareFn;
  14835. }
  14836. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14837. /**
  14838. * Set the opaque sort comparison function.
  14839. * If null the sub meshes will be render in the order they were created
  14840. */
  14841. set: function (value) {
  14842. this._opaqueSortCompareFn = value;
  14843. if (value) {
  14844. this._renderOpaque = this.renderOpaqueSorted;
  14845. }
  14846. else {
  14847. this._renderOpaque = RenderingGroup.renderUnsorted;
  14848. }
  14849. },
  14850. enumerable: true,
  14851. configurable: true
  14852. });
  14853. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14854. /**
  14855. * Set the alpha test sort comparison function.
  14856. * If null the sub meshes will be render in the order they were created
  14857. */
  14858. set: function (value) {
  14859. this._alphaTestSortCompareFn = value;
  14860. if (value) {
  14861. this._renderAlphaTest = this.renderAlphaTestSorted;
  14862. }
  14863. else {
  14864. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14865. }
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14871. /**
  14872. * Set the transparent sort comparison function.
  14873. * If null the sub meshes will be render in the order they were created
  14874. */
  14875. set: function (value) {
  14876. if (value) {
  14877. this._transparentSortCompareFn = value;
  14878. }
  14879. else {
  14880. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14881. }
  14882. this._renderTransparent = this.renderTransparentSorted;
  14883. },
  14884. enumerable: true,
  14885. configurable: true
  14886. });
  14887. /**
  14888. * Render all the sub meshes contained in the group.
  14889. * @param customRenderFunction Used to override the default render behaviour of the group.
  14890. * @returns true if rendered some submeshes.
  14891. */
  14892. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14893. if (customRenderFunction) {
  14894. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14895. return;
  14896. }
  14897. var engine = this._scene.getEngine();
  14898. // Opaque
  14899. if (this._opaqueSubMeshes.length !== 0) {
  14900. this._renderOpaque(this._opaqueSubMeshes);
  14901. }
  14902. // Alpha test
  14903. if (this._alphaTestSubMeshes.length !== 0) {
  14904. engine.setAlphaTesting(true);
  14905. this._renderAlphaTest(this._alphaTestSubMeshes);
  14906. engine.setAlphaTesting(false);
  14907. }
  14908. var stencilState = engine.getStencilBuffer();
  14909. engine.setStencilBuffer(false);
  14910. // Sprites
  14911. if (renderSprites) {
  14912. this._renderSprites();
  14913. }
  14914. // Particles
  14915. if (renderParticles) {
  14916. this._renderParticles(activeMeshes);
  14917. }
  14918. if (this.onBeforeTransparentRendering) {
  14919. this.onBeforeTransparentRendering();
  14920. }
  14921. // Transparent
  14922. if (this._transparentSubMeshes.length !== 0) {
  14923. this._renderTransparent(this._transparentSubMeshes);
  14924. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14925. }
  14926. engine.setStencilBuffer(stencilState);
  14927. // Edges
  14928. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14929. this._edgesRenderers.data[edgesRendererIndex].render();
  14930. }
  14931. };
  14932. /**
  14933. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14934. * @param subMeshes The submeshes to render
  14935. */
  14936. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14937. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14938. };
  14939. /**
  14940. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14941. * @param subMeshes The submeshes to render
  14942. */
  14943. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14944. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14945. };
  14946. /**
  14947. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14948. * @param subMeshes The submeshes to render
  14949. */
  14950. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14951. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14952. };
  14953. /**
  14954. * Renders the submeshes in a specified order.
  14955. * @param subMeshes The submeshes to sort before render
  14956. * @param sortCompareFn The comparison function use to sort
  14957. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14958. * @param transparent Specifies to activate blending if true
  14959. */
  14960. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14961. var subIndex = 0;
  14962. var subMesh;
  14963. for (; subIndex < subMeshes.length; subIndex++) {
  14964. subMesh = subMeshes.data[subIndex];
  14965. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14966. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14967. }
  14968. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14969. sortedArray.sort(sortCompareFn);
  14970. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14971. subMesh = sortedArray[subIndex];
  14972. subMesh.render(transparent);
  14973. }
  14974. };
  14975. /**
  14976. * Renders the submeshes in the order they were dispatched (no sort applied).
  14977. * @param subMeshes The submeshes to render
  14978. */
  14979. RenderingGroup.renderUnsorted = function (subMeshes) {
  14980. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14981. var submesh = subMeshes.data[subIndex];
  14982. submesh.render(false);
  14983. }
  14984. };
  14985. /**
  14986. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14987. * are rendered back to front if in the same alpha index.
  14988. *
  14989. * @param a The first submesh
  14990. * @param b The second submesh
  14991. * @returns The result of the comparison
  14992. */
  14993. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14994. // Alpha index first
  14995. if (a._alphaIndex > b._alphaIndex) {
  14996. return 1;
  14997. }
  14998. if (a._alphaIndex < b._alphaIndex) {
  14999. return -1;
  15000. }
  15001. // Then distance to camera
  15002. return RenderingGroup.backToFrontSortCompare(a, b);
  15003. };
  15004. /**
  15005. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15006. * are rendered back to front.
  15007. *
  15008. * @param a The first submesh
  15009. * @param b The second submesh
  15010. * @returns The result of the comparison
  15011. */
  15012. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15013. // Then distance to camera
  15014. if (a._distanceToCamera < b._distanceToCamera) {
  15015. return 1;
  15016. }
  15017. if (a._distanceToCamera > b._distanceToCamera) {
  15018. return -1;
  15019. }
  15020. return 0;
  15021. };
  15022. /**
  15023. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15024. * are rendered front to back (prevent overdraw).
  15025. *
  15026. * @param a The first submesh
  15027. * @param b The second submesh
  15028. * @returns The result of the comparison
  15029. */
  15030. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15031. // Then distance to camera
  15032. if (a._distanceToCamera < b._distanceToCamera) {
  15033. return -1;
  15034. }
  15035. if (a._distanceToCamera > b._distanceToCamera) {
  15036. return 1;
  15037. }
  15038. return 0;
  15039. };
  15040. /**
  15041. * Resets the different lists of submeshes to prepare a new frame.
  15042. */
  15043. RenderingGroup.prototype.prepare = function () {
  15044. this._opaqueSubMeshes.reset();
  15045. this._transparentSubMeshes.reset();
  15046. this._alphaTestSubMeshes.reset();
  15047. this._particleSystems.reset();
  15048. this._spriteManagers.reset();
  15049. this._edgesRenderers.reset();
  15050. };
  15051. RenderingGroup.prototype.dispose = function () {
  15052. this._opaqueSubMeshes.dispose();
  15053. this._transparentSubMeshes.dispose();
  15054. this._alphaTestSubMeshes.dispose();
  15055. this._particleSystems.dispose();
  15056. this._spriteManagers.dispose();
  15057. this._edgesRenderers.dispose();
  15058. };
  15059. /**
  15060. * Inserts the submesh in its correct queue depending on its material.
  15061. * @param subMesh The submesh to dispatch
  15062. */
  15063. RenderingGroup.prototype.dispatch = function (subMesh) {
  15064. var material = subMesh.getMaterial();
  15065. var mesh = subMesh.getMesh();
  15066. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15067. this._transparentSubMeshes.push(subMesh);
  15068. }
  15069. else if (material.needAlphaTesting()) {
  15070. this._alphaTestSubMeshes.push(subMesh);
  15071. }
  15072. else {
  15073. this._opaqueSubMeshes.push(subMesh); // Opaque
  15074. }
  15075. if (mesh._edgesRenderer) {
  15076. this._edgesRenderers.push(mesh._edgesRenderer);
  15077. }
  15078. };
  15079. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15080. this._spriteManagers.push(spriteManager);
  15081. };
  15082. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15083. this._particleSystems.push(particleSystem);
  15084. };
  15085. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15086. if (this._particleSystems.length === 0) {
  15087. return;
  15088. }
  15089. // Particles
  15090. var activeCamera = this._scene.activeCamera;
  15091. this._scene._particlesDuration.beginMonitoring();
  15092. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15093. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15094. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15095. continue;
  15096. }
  15097. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15098. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15099. }
  15100. }
  15101. this._scene._particlesDuration.endMonitoring(false);
  15102. };
  15103. RenderingGroup.prototype._renderSprites = function () {
  15104. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15105. return;
  15106. }
  15107. // Sprites
  15108. var activeCamera = this._scene.activeCamera;
  15109. this._scene._spritesDuration.beginMonitoring();
  15110. for (var id = 0; id < this._spriteManagers.length; id++) {
  15111. var spriteManager = this._spriteManagers.data[id];
  15112. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15113. spriteManager.render();
  15114. }
  15115. }
  15116. this._scene._spritesDuration.endMonitoring(false);
  15117. };
  15118. return RenderingGroup;
  15119. }());
  15120. BABYLON.RenderingGroup = RenderingGroup;
  15121. })(BABYLON || (BABYLON = {}));
  15122. //# sourceMappingURL=babylon.renderingGroup.js.map
  15123. var BABYLON;
  15124. (function (BABYLON) {
  15125. var ClickInfo = (function () {
  15126. function ClickInfo() {
  15127. this._singleClick = false;
  15128. this._doubleClick = false;
  15129. this._hasSwiped = false;
  15130. this._ignore = false;
  15131. }
  15132. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15133. get: function () {
  15134. return this._singleClick;
  15135. },
  15136. set: function (b) {
  15137. this._singleClick = b;
  15138. },
  15139. enumerable: true,
  15140. configurable: true
  15141. });
  15142. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15143. get: function () {
  15144. return this._doubleClick;
  15145. },
  15146. set: function (b) {
  15147. this._doubleClick = b;
  15148. },
  15149. enumerable: true,
  15150. configurable: true
  15151. });
  15152. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15153. get: function () {
  15154. return this._hasSwiped;
  15155. },
  15156. set: function (b) {
  15157. this._hasSwiped = b;
  15158. },
  15159. enumerable: true,
  15160. configurable: true
  15161. });
  15162. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15163. get: function () {
  15164. return this._ignore;
  15165. },
  15166. set: function (b) {
  15167. this._ignore = b;
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. return ClickInfo;
  15173. }());
  15174. var PointerEventTypes = (function () {
  15175. function PointerEventTypes() {
  15176. }
  15177. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15178. get: function () {
  15179. return PointerEventTypes._POINTERDOWN;
  15180. },
  15181. enumerable: true,
  15182. configurable: true
  15183. });
  15184. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15185. get: function () {
  15186. return PointerEventTypes._POINTERUP;
  15187. },
  15188. enumerable: true,
  15189. configurable: true
  15190. });
  15191. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15192. get: function () {
  15193. return PointerEventTypes._POINTERMOVE;
  15194. },
  15195. enumerable: true,
  15196. configurable: true
  15197. });
  15198. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15199. get: function () {
  15200. return PointerEventTypes._POINTERWHEEL;
  15201. },
  15202. enumerable: true,
  15203. configurable: true
  15204. });
  15205. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15206. get: function () {
  15207. return PointerEventTypes._POINTERPICK;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15213. get: function () {
  15214. return PointerEventTypes._POINTERTAP;
  15215. },
  15216. enumerable: true,
  15217. configurable: true
  15218. });
  15219. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15220. get: function () {
  15221. return PointerEventTypes._POINTERDOUBLETAP;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. return PointerEventTypes;
  15227. }());
  15228. PointerEventTypes._POINTERDOWN = 0x01;
  15229. PointerEventTypes._POINTERUP = 0x02;
  15230. PointerEventTypes._POINTERMOVE = 0x04;
  15231. PointerEventTypes._POINTERWHEEL = 0x08;
  15232. PointerEventTypes._POINTERPICK = 0x10;
  15233. PointerEventTypes._POINTERTAP = 0x20;
  15234. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15235. BABYLON.PointerEventTypes = PointerEventTypes;
  15236. var PointerInfoBase = (function () {
  15237. function PointerInfoBase(type, event) {
  15238. this.type = type;
  15239. this.event = event;
  15240. }
  15241. return PointerInfoBase;
  15242. }());
  15243. BABYLON.PointerInfoBase = PointerInfoBase;
  15244. /**
  15245. * This class is used to store pointer related info for the onPrePointerObservable event.
  15246. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15247. */
  15248. var PointerInfoPre = (function (_super) {
  15249. __extends(PointerInfoPre, _super);
  15250. function PointerInfoPre(type, event, localX, localY) {
  15251. var _this = _super.call(this, type, event) || this;
  15252. _this.skipOnPointerObservable = false;
  15253. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15254. return _this;
  15255. }
  15256. return PointerInfoPre;
  15257. }(PointerInfoBase));
  15258. BABYLON.PointerInfoPre = PointerInfoPre;
  15259. /**
  15260. * This type contains all the data related to a pointer event in Babylon.js.
  15261. * 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.
  15262. */
  15263. var PointerInfo = (function (_super) {
  15264. __extends(PointerInfo, _super);
  15265. function PointerInfo(type, event, pickInfo) {
  15266. var _this = _super.call(this, type, event) || this;
  15267. _this.pickInfo = pickInfo;
  15268. return _this;
  15269. }
  15270. return PointerInfo;
  15271. }(PointerInfoBase));
  15272. BABYLON.PointerInfo = PointerInfo;
  15273. /**
  15274. * This class is used by the onRenderingGroupObservable
  15275. */
  15276. var RenderingGroupInfo = (function () {
  15277. function RenderingGroupInfo() {
  15278. }
  15279. return RenderingGroupInfo;
  15280. }());
  15281. /**
  15282. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15283. * This stage will be fired no matter what
  15284. */
  15285. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15286. /**
  15287. * Called before opaque object are rendered.
  15288. * This stage will be fired only if there's 3D Opaque content to render
  15289. */
  15290. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15291. /**
  15292. * Called after the opaque objects are rendered and before the transparent ones
  15293. * This stage will be fired only if there's 3D transparent content to render
  15294. */
  15295. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15296. /**
  15297. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15298. * This stage will be fired no matter what
  15299. */
  15300. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15301. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15302. /**
  15303. * Represents a scene to be rendered by the engine.
  15304. * @see http://doc.babylonjs.com/page.php?p=21911
  15305. */
  15306. var Scene = (function () {
  15307. /**
  15308. * @constructor
  15309. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15310. */
  15311. function Scene(engine) {
  15312. // Members
  15313. this.autoClear = true;
  15314. this.autoClearDepthAndStencil = true;
  15315. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15316. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15317. this.forceWireframe = false;
  15318. this._forcePointsCloud = false;
  15319. this.forceShowBoundingBoxes = false;
  15320. this.animationsEnabled = true;
  15321. this.constantlyUpdateMeshUnderPointer = false;
  15322. this.hoverCursor = "pointer";
  15323. // Metadata
  15324. this.metadata = null;
  15325. // Events
  15326. /**
  15327. * An event triggered when the scene is disposed.
  15328. * @type {BABYLON.Observable}
  15329. */
  15330. this.onDisposeObservable = new BABYLON.Observable();
  15331. /**
  15332. * An event triggered before rendering the scene
  15333. * @type {BABYLON.Observable}
  15334. */
  15335. this.onBeforeRenderObservable = new BABYLON.Observable();
  15336. /**
  15337. * An event triggered after rendering the scene
  15338. * @type {BABYLON.Observable}
  15339. */
  15340. this.onAfterRenderObservable = new BABYLON.Observable();
  15341. /**
  15342. * An event triggered when the scene is ready
  15343. * @type {BABYLON.Observable}
  15344. */
  15345. this.onReadyObservable = new BABYLON.Observable();
  15346. /**
  15347. * An event triggered before rendering a camera
  15348. * @type {BABYLON.Observable}
  15349. */
  15350. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15351. /**
  15352. * An event triggered after rendering a camera
  15353. * @type {BABYLON.Observable}
  15354. */
  15355. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15356. /**
  15357. * An event triggered when a camera is created
  15358. * @type {BABYLON.Observable}
  15359. */
  15360. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15361. /**
  15362. * An event triggered when a camera is removed
  15363. * @type {BABYLON.Observable}
  15364. */
  15365. this.onCameraRemovedObservable = new BABYLON.Observable();
  15366. /**
  15367. * An event triggered when a light is created
  15368. * @type {BABYLON.Observable}
  15369. */
  15370. this.onNewLightAddedObservable = new BABYLON.Observable();
  15371. /**
  15372. * An event triggered when a light is removed
  15373. * @type {BABYLON.Observable}
  15374. */
  15375. this.onLightRemovedObservable = new BABYLON.Observable();
  15376. /**
  15377. * An event triggered when a geometry is created
  15378. * @type {BABYLON.Observable}
  15379. */
  15380. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15381. /**
  15382. * An event triggered when a geometry is removed
  15383. * @type {BABYLON.Observable}
  15384. */
  15385. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15386. /**
  15387. * An event triggered when a mesh is created
  15388. * @type {BABYLON.Observable}
  15389. */
  15390. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15391. /**
  15392. * An event triggered when a mesh is removed
  15393. * @type {BABYLON.Observable}
  15394. */
  15395. this.onMeshRemovedObservable = new BABYLON.Observable();
  15396. /**
  15397. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15398. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15399. * 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)
  15400. */
  15401. this.onRenderingGroupObservable = new BABYLON.Observable();
  15402. // Animations
  15403. this.animations = [];
  15404. /**
  15405. * 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).
  15406. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15407. */
  15408. this.onPrePointerObservable = new BABYLON.Observable();
  15409. /**
  15410. * Observable event triggered each time an input event is received from the rendering canvas
  15411. */
  15412. this.onPointerObservable = new BABYLON.Observable();
  15413. this._meshPickProceed = false;
  15414. this._previousHasSwiped = false;
  15415. this._currentPickResult = null;
  15416. this._previousPickResult = null;
  15417. this._isButtonPressed = false;
  15418. this._doubleClickOccured = false;
  15419. 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
  15420. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15421. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15422. this._startingPointerTime = 0;
  15423. this._previousStartingPointerTime = 0;
  15424. // Coordinate system
  15425. /**
  15426. * use right-handed coordinate system on this scene.
  15427. * @type {boolean}
  15428. */
  15429. this._useRightHandedSystem = false;
  15430. // Fog
  15431. /**
  15432. * is fog enabled on this scene.
  15433. * @type {boolean}
  15434. */
  15435. this._fogEnabled = true;
  15436. this._fogMode = Scene.FOGMODE_NONE;
  15437. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15438. this.fogDensity = 0.1;
  15439. this.fogStart = 0;
  15440. this.fogEnd = 1000.0;
  15441. // Lights
  15442. /**
  15443. * is shadow enabled on this scene.
  15444. * @type {boolean}
  15445. */
  15446. this._shadowsEnabled = true;
  15447. /**
  15448. * is light enabled on this scene.
  15449. * @type {boolean}
  15450. */
  15451. this._lightsEnabled = true;
  15452. /**
  15453. * All of the lights added to this scene.
  15454. * @see BABYLON.Light
  15455. * @type {BABYLON.Light[]}
  15456. */
  15457. this.lights = new Array();
  15458. // Cameras
  15459. /**
  15460. * All of the cameras added to this scene.
  15461. * @see BABYLON.Camera
  15462. * @type {BABYLON.Camera[]}
  15463. */
  15464. this.cameras = new Array();
  15465. this.activeCameras = new Array();
  15466. // Meshes
  15467. /**
  15468. * All of the (abstract) meshes added to this scene.
  15469. * @see BABYLON.AbstractMesh
  15470. * @type {BABYLON.AbstractMesh[]}
  15471. */
  15472. this.meshes = new Array();
  15473. // Geometries
  15474. this._geometries = new Array();
  15475. this.materials = new Array();
  15476. this.multiMaterials = new Array();
  15477. // Textures
  15478. this._texturesEnabled = true;
  15479. this.textures = new Array();
  15480. // Particles
  15481. this.particlesEnabled = true;
  15482. this.particleSystems = new Array();
  15483. // Sprites
  15484. this.spritesEnabled = true;
  15485. this.spriteManagers = new Array();
  15486. // Layers
  15487. this.layers = new Array();
  15488. this.highlightLayers = new Array();
  15489. // Skeletons
  15490. this._skeletonsEnabled = true;
  15491. this.skeletons = new Array();
  15492. // Morph targets
  15493. this.morphTargetManagers = new Array();
  15494. // Lens flares
  15495. this.lensFlaresEnabled = true;
  15496. this.lensFlareSystems = new Array();
  15497. // Collisions
  15498. this.collisionsEnabled = true;
  15499. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15500. // Postprocesses
  15501. this.postProcessesEnabled = true;
  15502. // Customs render targets
  15503. this.renderTargetsEnabled = true;
  15504. this.dumpNextRenderTargets = false;
  15505. this.customRenderTargets = new Array();
  15506. // Imported meshes
  15507. this.importedMeshesFiles = new Array();
  15508. // Probes
  15509. this.probesEnabled = true;
  15510. this.reflectionProbes = new Array();
  15511. this._actionManagers = new Array();
  15512. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15513. // Procedural textures
  15514. this.proceduralTexturesEnabled = true;
  15515. this._proceduralTextures = new Array();
  15516. this.soundTracks = new Array();
  15517. this._audioEnabled = true;
  15518. this._headphone = false;
  15519. // Performance counters
  15520. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15521. this._totalLightsCounter = new BABYLON.PerfCounter();
  15522. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15523. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15524. this._totalVertices = new BABYLON.PerfCounter();
  15525. this._activeIndices = new BABYLON.PerfCounter();
  15526. this._activeParticles = new BABYLON.PerfCounter();
  15527. this._lastFrameDuration = new BABYLON.PerfCounter();
  15528. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15529. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15530. this._particlesDuration = new BABYLON.PerfCounter();
  15531. this._renderDuration = new BABYLON.PerfCounter();
  15532. this._spritesDuration = new BABYLON.PerfCounter();
  15533. this._activeBones = new BABYLON.PerfCounter();
  15534. this._animationTime = 0;
  15535. this.animationTimeScale = 1;
  15536. this._renderId = 0;
  15537. this._executeWhenReadyTimeoutId = -1;
  15538. this._intermediateRendering = false;
  15539. this._viewUpdateFlag = -1;
  15540. this._projectionUpdateFlag = -1;
  15541. this._toBeDisposed = new BABYLON.SmartArray(256);
  15542. this._pendingData = []; //ANY
  15543. this._activeMeshes = new BABYLON.SmartArray(256);
  15544. this._processedMaterials = new BABYLON.SmartArray(256);
  15545. this._renderTargets = new BABYLON.SmartArray(256);
  15546. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15547. this._activeSkeletons = new BABYLON.SmartArray(32);
  15548. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15549. this._activeAnimatables = new Array();
  15550. this._transformMatrix = BABYLON.Matrix.Zero();
  15551. this.requireLightSorting = false;
  15552. this._uniqueIdCounter = 0;
  15553. this.offscreenRenderTarget = null;
  15554. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15555. this._engine.scenes.push(this);
  15556. this._uid = null;
  15557. this._renderingManager = new BABYLON.RenderingManager(this);
  15558. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15559. if (BABYLON.OutlineRenderer) {
  15560. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15561. }
  15562. this.attachControl();
  15563. if (BABYLON.SoundTrack) {
  15564. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15565. }
  15566. //simplification queue
  15567. if (BABYLON.SimplificationQueue) {
  15568. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15569. }
  15570. //collision coordinator initialization. For now legacy per default.
  15571. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15572. // Uniform Buffer
  15573. this._createUbo();
  15574. }
  15575. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15576. get: function () {
  15577. return Scene._FOGMODE_NONE;
  15578. },
  15579. enumerable: true,
  15580. configurable: true
  15581. });
  15582. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15583. get: function () {
  15584. return Scene._FOGMODE_EXP;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15590. get: function () {
  15591. return Scene._FOGMODE_EXP2;
  15592. },
  15593. enumerable: true,
  15594. configurable: true
  15595. });
  15596. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15597. get: function () {
  15598. return Scene._FOGMODE_LINEAR;
  15599. },
  15600. enumerable: true,
  15601. configurable: true
  15602. });
  15603. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15604. /**
  15605. * Texture used in all pbr material as the reflection texture.
  15606. * As in the majority of the scene they are the same (exception for multi room and so on),
  15607. * this is easier to reference from here than from all the materials.
  15608. */
  15609. get: function () {
  15610. return this._environmentTexture;
  15611. },
  15612. /**
  15613. * Texture used in all pbr material as the reflection texture.
  15614. * As in the majority of the scene they are the same (exception for multi room and so on),
  15615. * this is easier to set here than in all the materials.
  15616. */
  15617. set: function (value) {
  15618. this._environmentTexture = value;
  15619. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15620. },
  15621. enumerable: true,
  15622. configurable: true
  15623. });
  15624. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15625. get: function () {
  15626. return this._forcePointsCloud;
  15627. },
  15628. set: function (value) {
  15629. if (this._forcePointsCloud === value) {
  15630. return;
  15631. }
  15632. this._forcePointsCloud = value;
  15633. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15634. },
  15635. enumerable: true,
  15636. configurable: true
  15637. });
  15638. Object.defineProperty(Scene.prototype, "onDispose", {
  15639. set: function (callback) {
  15640. if (this._onDisposeObserver) {
  15641. this.onDisposeObservable.remove(this._onDisposeObserver);
  15642. }
  15643. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15644. },
  15645. enumerable: true,
  15646. configurable: true
  15647. });
  15648. Object.defineProperty(Scene.prototype, "beforeRender", {
  15649. set: function (callback) {
  15650. if (this._onBeforeRenderObserver) {
  15651. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15652. }
  15653. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15654. },
  15655. enumerable: true,
  15656. configurable: true
  15657. });
  15658. Object.defineProperty(Scene.prototype, "afterRender", {
  15659. set: function (callback) {
  15660. if (this._onAfterRenderObserver) {
  15661. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15662. }
  15663. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15669. set: function (callback) {
  15670. if (this._onBeforeCameraRenderObserver) {
  15671. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15672. }
  15673. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15679. set: function (callback) {
  15680. if (this._onAfterCameraRenderObserver) {
  15681. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15682. }
  15683. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15689. get: function () {
  15690. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15696. get: function () {
  15697. return this._useRightHandedSystem;
  15698. },
  15699. set: function (value) {
  15700. if (this._useRightHandedSystem === value) {
  15701. return;
  15702. }
  15703. this._useRightHandedSystem = value;
  15704. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15710. get: function () {
  15711. return this._fogEnabled;
  15712. },
  15713. set: function (value) {
  15714. if (this._fogEnabled === value) {
  15715. return;
  15716. }
  15717. this._fogEnabled = value;
  15718. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15719. },
  15720. enumerable: true,
  15721. configurable: true
  15722. });
  15723. Object.defineProperty(Scene.prototype, "fogMode", {
  15724. get: function () {
  15725. return this._fogMode;
  15726. },
  15727. set: function (value) {
  15728. if (this._fogMode === value) {
  15729. return;
  15730. }
  15731. this._fogMode = value;
  15732. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15738. get: function () {
  15739. return this._shadowsEnabled;
  15740. },
  15741. set: function (value) {
  15742. if (this._shadowsEnabled === value) {
  15743. return;
  15744. }
  15745. this._shadowsEnabled = value;
  15746. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15752. get: function () {
  15753. return this._lightsEnabled;
  15754. },
  15755. set: function (value) {
  15756. if (this._lightsEnabled === value) {
  15757. return;
  15758. }
  15759. this._lightsEnabled = value;
  15760. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15766. get: function () {
  15767. if (!this._defaultMaterial) {
  15768. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15769. }
  15770. return this._defaultMaterial;
  15771. },
  15772. set: function (value) {
  15773. this._defaultMaterial = value;
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15779. get: function () {
  15780. return this._texturesEnabled;
  15781. },
  15782. set: function (value) {
  15783. if (this._texturesEnabled === value) {
  15784. return;
  15785. }
  15786. this._texturesEnabled = value;
  15787. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15793. get: function () {
  15794. return this._skeletonsEnabled;
  15795. },
  15796. set: function (value) {
  15797. if (this._skeletonsEnabled === value) {
  15798. return;
  15799. }
  15800. this._skeletonsEnabled = value;
  15801. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15807. get: function () {
  15808. if (!this._postProcessRenderPipelineManager) {
  15809. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15810. }
  15811. return this._postProcessRenderPipelineManager;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15817. get: function () {
  15818. return this._frustumPlanes;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Object.defineProperty(Scene.prototype, "debugLayer", {
  15824. // Properties
  15825. get: function () {
  15826. if (!this._debugLayer) {
  15827. this._debugLayer = new BABYLON.DebugLayer(this);
  15828. }
  15829. return this._debugLayer;
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15835. get: function () {
  15836. return this._workerCollisions;
  15837. },
  15838. set: function (enabled) {
  15839. if (!BABYLON.CollisionCoordinatorLegacy) {
  15840. return;
  15841. }
  15842. enabled = (enabled && !!Worker);
  15843. this._workerCollisions = enabled;
  15844. if (this.collisionCoordinator) {
  15845. this.collisionCoordinator.destroy();
  15846. }
  15847. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15848. this.collisionCoordinator.init(this);
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15854. get: function () {
  15855. return this._selectionOctree;
  15856. },
  15857. enumerable: true,
  15858. configurable: true
  15859. });
  15860. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15861. /**
  15862. * The mesh that is currently under the pointer.
  15863. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15864. */
  15865. get: function () {
  15866. return this._pointerOverMesh;
  15867. },
  15868. enumerable: true,
  15869. configurable: true
  15870. });
  15871. Object.defineProperty(Scene.prototype, "pointerX", {
  15872. /**
  15873. * Current on-screen X position of the pointer
  15874. * @return {number} X position of the pointer
  15875. */
  15876. get: function () {
  15877. return this._pointerX;
  15878. },
  15879. enumerable: true,
  15880. configurable: true
  15881. });
  15882. Object.defineProperty(Scene.prototype, "pointerY", {
  15883. /**
  15884. * Current on-screen Y position of the pointer
  15885. * @return {number} Y position of the pointer
  15886. */
  15887. get: function () {
  15888. return this._pointerY;
  15889. },
  15890. enumerable: true,
  15891. configurable: true
  15892. });
  15893. Scene.prototype.getCachedMaterial = function () {
  15894. return this._cachedMaterial;
  15895. };
  15896. Scene.prototype.getCachedEffect = function () {
  15897. return this._cachedEffect;
  15898. };
  15899. Scene.prototype.getCachedVisibility = function () {
  15900. return this._cachedVisibility;
  15901. };
  15902. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15903. if (visibility === void 0) { visibility = 0; }
  15904. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15905. };
  15906. Scene.prototype.getBoundingBoxRenderer = function () {
  15907. if (!this._boundingBoxRenderer) {
  15908. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15909. }
  15910. return this._boundingBoxRenderer;
  15911. };
  15912. Scene.prototype.getOutlineRenderer = function () {
  15913. return this._outlineRenderer;
  15914. };
  15915. Scene.prototype.getEngine = function () {
  15916. return this._engine;
  15917. };
  15918. Scene.prototype.getTotalVertices = function () {
  15919. return this._totalVertices.current;
  15920. };
  15921. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15922. get: function () {
  15923. return this._totalVertices;
  15924. },
  15925. enumerable: true,
  15926. configurable: true
  15927. });
  15928. Scene.prototype.getActiveIndices = function () {
  15929. return this._activeIndices.current;
  15930. };
  15931. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15932. get: function () {
  15933. return this._activeIndices;
  15934. },
  15935. enumerable: true,
  15936. configurable: true
  15937. });
  15938. Scene.prototype.getActiveParticles = function () {
  15939. return this._activeParticles.current;
  15940. };
  15941. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15942. get: function () {
  15943. return this._activeParticles;
  15944. },
  15945. enumerable: true,
  15946. configurable: true
  15947. });
  15948. Scene.prototype.getActiveBones = function () {
  15949. return this._activeBones.current;
  15950. };
  15951. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15952. get: function () {
  15953. return this._activeBones;
  15954. },
  15955. enumerable: true,
  15956. configurable: true
  15957. });
  15958. // Stats
  15959. Scene.prototype.getLastFrameDuration = function () {
  15960. return this._lastFrameDuration.current;
  15961. };
  15962. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15963. get: function () {
  15964. return this._lastFrameDuration;
  15965. },
  15966. enumerable: true,
  15967. configurable: true
  15968. });
  15969. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15970. return this._evaluateActiveMeshesDuration.current;
  15971. };
  15972. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15973. get: function () {
  15974. return this._evaluateActiveMeshesDuration;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Scene.prototype.getActiveMeshes = function () {
  15980. return this._activeMeshes;
  15981. };
  15982. Scene.prototype.getRenderTargetsDuration = function () {
  15983. return this._renderTargetsDuration.current;
  15984. };
  15985. Scene.prototype.getRenderDuration = function () {
  15986. return this._renderDuration.current;
  15987. };
  15988. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15989. get: function () {
  15990. return this._renderDuration;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Scene.prototype.getParticlesDuration = function () {
  15996. return this._particlesDuration.current;
  15997. };
  15998. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15999. get: function () {
  16000. return this._particlesDuration;
  16001. },
  16002. enumerable: true,
  16003. configurable: true
  16004. });
  16005. Scene.prototype.getSpritesDuration = function () {
  16006. return this._spritesDuration.current;
  16007. };
  16008. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16009. get: function () {
  16010. return this._spritesDuration;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Scene.prototype.getAnimationRatio = function () {
  16016. return this._animationRatio;
  16017. };
  16018. Scene.prototype.getRenderId = function () {
  16019. return this._renderId;
  16020. };
  16021. Scene.prototype.incrementRenderId = function () {
  16022. this._renderId++;
  16023. };
  16024. Scene.prototype._updatePointerPosition = function (evt) {
  16025. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16026. this._pointerX = evt.clientX - canvasRect.left;
  16027. this._pointerY = evt.clientY - canvasRect.top;
  16028. this._unTranslatedPointerX = this._pointerX;
  16029. this._unTranslatedPointerY = this._pointerY;
  16030. if (this.cameraToUseForPointers) {
  16031. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16032. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16033. }
  16034. };
  16035. Scene.prototype._createUbo = function () {
  16036. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16037. this._sceneUbo.addUniform("viewProjection", 16);
  16038. this._sceneUbo.addUniform("view", 16);
  16039. };
  16040. // Pointers handling
  16041. /**
  16042. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16043. * @param attachUp defines if you want to attach events to pointerup
  16044. * @param attachDown defines if you want to attach events to pointerdown
  16045. * @param attachMove defines if you want to attach events to pointermove
  16046. */
  16047. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16048. var _this = this;
  16049. if (attachUp === void 0) { attachUp = true; }
  16050. if (attachDown === void 0) { attachDown = true; }
  16051. if (attachMove === void 0) { attachMove = true; }
  16052. this._initActionManager = function (act, clickInfo) {
  16053. if (!_this._meshPickProceed) {
  16054. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16055. _this._currentPickResult = pickResult;
  16056. if (pickResult) {
  16057. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16058. }
  16059. _this._meshPickProceed = true;
  16060. }
  16061. return act;
  16062. };
  16063. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16064. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16065. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16066. btn !== _this._previousButtonPressed) {
  16067. _this._doubleClickOccured = false;
  16068. clickInfo.singleClick = true;
  16069. clickInfo.ignore = false;
  16070. cb(clickInfo, _this._currentPickResult);
  16071. }
  16072. };
  16073. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16074. var clickInfo = new ClickInfo();
  16075. _this._currentPickResult = null;
  16076. var act;
  16077. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16078. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16079. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16080. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16081. act = _this._initActionManager(act, clickInfo);
  16082. if (act)
  16083. checkPicking = act.hasPickTriggers;
  16084. }
  16085. if (checkPicking) {
  16086. var btn = evt.button;
  16087. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16088. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16089. if (!clickInfo.hasSwiped) {
  16090. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16091. if (!checkSingleClickImmediately) {
  16092. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16093. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16094. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16095. act = _this._initActionManager(act, clickInfo);
  16096. if (act)
  16097. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16098. }
  16099. }
  16100. if (checkSingleClickImmediately) {
  16101. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16102. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16103. btn !== _this._previousButtonPressed) {
  16104. clickInfo.singleClick = true;
  16105. cb(clickInfo, _this._currentPickResult);
  16106. }
  16107. }
  16108. else {
  16109. // wait that no double click has been raised during the double click delay
  16110. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16111. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16112. }
  16113. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16114. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16115. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16116. act = _this._initActionManager(act, clickInfo);
  16117. if (act)
  16118. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16119. }
  16120. if (checkDoubleClick) {
  16121. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16122. if (btn === _this._previousButtonPressed &&
  16123. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16124. !_this._doubleClickOccured) {
  16125. // pointer has not moved for 2 clicks, it's a double click
  16126. if (!clickInfo.hasSwiped &&
  16127. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16128. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16129. _this._previousStartingPointerTime = 0;
  16130. _this._doubleClickOccured = true;
  16131. clickInfo.doubleClick = true;
  16132. clickInfo.ignore = false;
  16133. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16134. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16135. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16136. cb(clickInfo, _this._currentPickResult);
  16137. }
  16138. else {
  16139. _this._doubleClickOccured = false;
  16140. _this._previousStartingPointerTime = _this._startingPointerTime;
  16141. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16142. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16143. _this._previousButtonPressed = btn;
  16144. _this._previousHasSwiped = clickInfo.hasSwiped;
  16145. if (Scene.ExclusiveDoubleClickMode) {
  16146. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16147. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16148. }
  16149. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16150. cb(clickInfo, _this._previousPickResult);
  16151. }
  16152. else {
  16153. cb(clickInfo, _this._currentPickResult);
  16154. }
  16155. }
  16156. }
  16157. else {
  16158. _this._doubleClickOccured = false;
  16159. _this._previousStartingPointerTime = _this._startingPointerTime;
  16160. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16161. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16162. _this._previousButtonPressed = btn;
  16163. _this._previousHasSwiped = clickInfo.hasSwiped;
  16164. }
  16165. }
  16166. }
  16167. }
  16168. clickInfo.ignore = true;
  16169. cb(clickInfo, _this._currentPickResult);
  16170. };
  16171. var spritePredicate = function (sprite) {
  16172. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16173. };
  16174. this._onPointerMove = function (evt) {
  16175. _this._updatePointerPosition(evt);
  16176. // PreObservable support
  16177. if (_this.onPrePointerObservable.hasObservers()) {
  16178. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16179. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16180. _this.onPrePointerObservable.notifyObservers(pi, type);
  16181. if (pi.skipOnPointerObservable) {
  16182. return;
  16183. }
  16184. }
  16185. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16186. return;
  16187. }
  16188. var canvas = _this._engine.getRenderingCanvas();
  16189. if (!_this.pointerMovePredicate) {
  16190. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16191. }
  16192. // Meshes
  16193. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16194. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16195. _this.setPointerOverSprite(null);
  16196. _this.setPointerOverMesh(pickResult.pickedMesh);
  16197. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16198. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16199. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16200. }
  16201. else {
  16202. canvas.style.cursor = _this.hoverCursor;
  16203. }
  16204. }
  16205. else {
  16206. canvas.style.cursor = "";
  16207. }
  16208. }
  16209. else {
  16210. _this.setPointerOverMesh(null);
  16211. // Sprites
  16212. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16213. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16214. _this.setPointerOverSprite(pickResult.pickedSprite);
  16215. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16216. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16217. }
  16218. else {
  16219. canvas.style.cursor = _this.hoverCursor;
  16220. }
  16221. }
  16222. else {
  16223. _this.setPointerOverSprite(null);
  16224. // Restore pointer
  16225. canvas.style.cursor = "";
  16226. }
  16227. }
  16228. if (_this.onPointerMove) {
  16229. _this.onPointerMove(evt, pickResult);
  16230. }
  16231. if (_this.onPointerObservable.hasObservers()) {
  16232. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16233. var pi = new PointerInfo(type, evt, pickResult);
  16234. _this.onPointerObservable.notifyObservers(pi, type);
  16235. }
  16236. };
  16237. this._onPointerDown = function (evt) {
  16238. _this._isButtonPressed = true;
  16239. _this._pickedDownMesh = null;
  16240. _this._meshPickProceed = false;
  16241. _this._updatePointerPosition(evt);
  16242. // PreObservable support
  16243. if (_this.onPrePointerObservable.hasObservers()) {
  16244. var type = PointerEventTypes.POINTERDOWN;
  16245. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16246. _this.onPrePointerObservable.notifyObservers(pi, type);
  16247. if (pi.skipOnPointerObservable) {
  16248. return;
  16249. }
  16250. }
  16251. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16252. return;
  16253. }
  16254. _this._startingPointerPosition.x = _this._pointerX;
  16255. _this._startingPointerPosition.y = _this._pointerY;
  16256. _this._startingPointerTime = new Date().getTime();
  16257. if (!_this.pointerDownPredicate) {
  16258. _this.pointerDownPredicate = function (mesh) {
  16259. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16260. };
  16261. }
  16262. // Meshes
  16263. _this._pickedDownMesh = null;
  16264. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16265. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16266. _this._pickedDownMesh = pickResult.pickedMesh;
  16267. var actionManager = pickResult.pickedMesh.actionManager;
  16268. if (actionManager) {
  16269. if (actionManager.hasPickTriggers) {
  16270. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16271. switch (evt.button) {
  16272. case 0:
  16273. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16274. break;
  16275. case 1:
  16276. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16277. break;
  16278. case 2:
  16279. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16280. break;
  16281. }
  16282. }
  16283. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16284. window.setTimeout((function () {
  16285. var _this = this;
  16286. 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);
  16287. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16288. if (this._isButtonPressed &&
  16289. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16290. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16291. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16292. this._startingPointerTime = 0;
  16293. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16294. }
  16295. }
  16296. }).bind(_this), Scene.LongPressDelay);
  16297. }
  16298. }
  16299. }
  16300. if (_this.onPointerDown) {
  16301. _this.onPointerDown(evt, pickResult);
  16302. }
  16303. if (_this.onPointerObservable.hasObservers()) {
  16304. var type = PointerEventTypes.POINTERDOWN;
  16305. var pi = new PointerInfo(type, evt, pickResult);
  16306. _this.onPointerObservable.notifyObservers(pi, type);
  16307. }
  16308. // Sprites
  16309. _this._pickedDownSprite = null;
  16310. if (_this.spriteManagers.length > 0) {
  16311. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16312. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16313. if (pickResult.pickedSprite.actionManager) {
  16314. _this._pickedDownSprite = pickResult.pickedSprite;
  16315. switch (evt.button) {
  16316. case 0:
  16317. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16318. break;
  16319. case 1:
  16320. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16321. break;
  16322. case 2:
  16323. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16324. break;
  16325. }
  16326. if (pickResult.pickedSprite.actionManager) {
  16327. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16328. }
  16329. }
  16330. }
  16331. }
  16332. };
  16333. this._onPointerUp = function (evt) {
  16334. _this._isButtonPressed = false;
  16335. _this._pickedUpMesh = null;
  16336. _this._meshPickProceed = false;
  16337. _this._updatePointerPosition(evt);
  16338. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16339. // PreObservable support
  16340. if (this.onPrePointerObservable.hasObservers()) {
  16341. if (!clickInfo.ignore) {
  16342. if (!clickInfo.hasSwiped) {
  16343. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16344. var type = PointerEventTypes.POINTERTAP;
  16345. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16346. this.onPrePointerObservable.notifyObservers(pi, type);
  16347. if (pi.skipOnPointerObservable) {
  16348. return;
  16349. }
  16350. }
  16351. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16352. var type = PointerEventTypes.POINTERDOUBLETAP;
  16353. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16354. this.onPrePointerObservable.notifyObservers(pi, type);
  16355. if (pi.skipOnPointerObservable) {
  16356. return;
  16357. }
  16358. }
  16359. }
  16360. }
  16361. else {
  16362. var type = PointerEventTypes.POINTERUP;
  16363. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16364. this.onPrePointerObservable.notifyObservers(pi, type);
  16365. if (pi.skipOnPointerObservable) {
  16366. return;
  16367. }
  16368. }
  16369. }
  16370. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16371. return;
  16372. }
  16373. if (!this.pointerUpPredicate) {
  16374. this.pointerUpPredicate = function (mesh) {
  16375. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16376. };
  16377. }
  16378. // Meshes
  16379. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16380. this._initActionManager(null, clickInfo);
  16381. }
  16382. if (!pickResult) {
  16383. pickResult = this._currentPickResult;
  16384. }
  16385. if (pickResult && pickResult && pickResult.pickedMesh) {
  16386. this._pickedUpMesh = pickResult.pickedMesh;
  16387. if (this._pickedDownMesh === this._pickedUpMesh) {
  16388. if (this.onPointerPick) {
  16389. this.onPointerPick(evt, pickResult);
  16390. }
  16391. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16392. var type = PointerEventTypes.POINTERPICK;
  16393. var pi = new PointerInfo(type, evt, pickResult);
  16394. this.onPointerObservable.notifyObservers(pi, type);
  16395. }
  16396. }
  16397. if (pickResult.pickedMesh.actionManager) {
  16398. if (clickInfo.ignore) {
  16399. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16400. }
  16401. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16402. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16403. }
  16404. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16405. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16406. }
  16407. }
  16408. }
  16409. if (this._pickedDownMesh &&
  16410. this._pickedDownMesh.actionManager &&
  16411. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16412. this._pickedDownMesh !== this._pickedUpMesh) {
  16413. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16414. }
  16415. if (this.onPointerUp) {
  16416. this.onPointerUp(evt, pickResult);
  16417. }
  16418. if (this.onPointerObservable.hasObservers()) {
  16419. if (!clickInfo.ignore) {
  16420. if (!clickInfo.hasSwiped) {
  16421. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16422. var type = PointerEventTypes.POINTERTAP;
  16423. var pi = new PointerInfo(type, evt, pickResult);
  16424. this.onPointerObservable.notifyObservers(pi, type);
  16425. }
  16426. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16427. var type = PointerEventTypes.POINTERDOUBLETAP;
  16428. var pi = new PointerInfo(type, evt, pickResult);
  16429. this.onPointerObservable.notifyObservers(pi, type);
  16430. }
  16431. }
  16432. }
  16433. else {
  16434. var type = PointerEventTypes.POINTERUP;
  16435. var pi = new PointerInfo(type, evt, pickResult);
  16436. this.onPointerObservable.notifyObservers(pi, type);
  16437. }
  16438. }
  16439. // Sprites
  16440. if (this.spriteManagers.length > 0) {
  16441. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16442. if (pickResult.hit && pickResult.pickedSprite) {
  16443. if (pickResult.pickedSprite.actionManager) {
  16444. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16445. if (pickResult.pickedSprite.actionManager) {
  16446. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16447. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16448. }
  16449. }
  16450. }
  16451. }
  16452. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16453. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16454. }
  16455. }
  16456. this._previousPickResult = this._currentPickResult;
  16457. }).bind(_this));
  16458. };
  16459. this._onKeyDown = function (evt) {
  16460. if (_this.actionManager) {
  16461. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16462. }
  16463. };
  16464. this._onKeyUp = function (evt) {
  16465. if (_this.actionManager) {
  16466. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16467. }
  16468. };
  16469. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16470. var canvas = this._engine.getRenderingCanvas();
  16471. if (attachMove) {
  16472. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16473. // Wheel
  16474. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16475. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16476. }
  16477. if (attachDown) {
  16478. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16479. }
  16480. if (attachUp) {
  16481. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16482. }
  16483. canvas.tabIndex = 1;
  16484. canvas.addEventListener("keydown", this._onKeyDown, false);
  16485. canvas.addEventListener("keyup", this._onKeyUp, false);
  16486. };
  16487. Scene.prototype.detachControl = function () {
  16488. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16489. var canvas = this._engine.getRenderingCanvas();
  16490. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16491. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16492. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16493. // Wheel
  16494. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16495. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16496. canvas.removeEventListener("keydown", this._onKeyDown);
  16497. canvas.removeEventListener("keyup", this._onKeyUp);
  16498. };
  16499. // Ready
  16500. Scene.prototype.isReady = function () {
  16501. if (this._pendingData.length > 0) {
  16502. return false;
  16503. }
  16504. var index;
  16505. // Geometries
  16506. for (index = 0; index < this._geometries.length; index++) {
  16507. var geometry = this._geometries[index];
  16508. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16509. return false;
  16510. }
  16511. }
  16512. // Meshes
  16513. for (index = 0; index < this.meshes.length; index++) {
  16514. var mesh = this.meshes[index];
  16515. if (!mesh.isEnabled()) {
  16516. continue;
  16517. }
  16518. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16519. continue;
  16520. }
  16521. if (!mesh.isReady()) {
  16522. return false;
  16523. }
  16524. var mat = mesh.material;
  16525. if (mat) {
  16526. if (!mat.isReady(mesh)) {
  16527. return false;
  16528. }
  16529. }
  16530. }
  16531. return true;
  16532. };
  16533. Scene.prototype.resetCachedMaterial = function () {
  16534. this._cachedMaterial = null;
  16535. this._cachedEffect = null;
  16536. this._cachedVisibility = null;
  16537. };
  16538. Scene.prototype.registerBeforeRender = function (func) {
  16539. this.onBeforeRenderObservable.add(func);
  16540. };
  16541. Scene.prototype.unregisterBeforeRender = function (func) {
  16542. this.onBeforeRenderObservable.removeCallback(func);
  16543. };
  16544. Scene.prototype.registerAfterRender = function (func) {
  16545. this.onAfterRenderObservable.add(func);
  16546. };
  16547. Scene.prototype.unregisterAfterRender = function (func) {
  16548. this.onAfterRenderObservable.removeCallback(func);
  16549. };
  16550. Scene.prototype._addPendingData = function (data) {
  16551. this._pendingData.push(data);
  16552. };
  16553. Scene.prototype._removePendingData = function (data) {
  16554. var index = this._pendingData.indexOf(data);
  16555. if (index !== -1) {
  16556. this._pendingData.splice(index, 1);
  16557. }
  16558. };
  16559. Scene.prototype.getWaitingItemsCount = function () {
  16560. return this._pendingData.length;
  16561. };
  16562. /**
  16563. * Registers a function to be executed when the scene is ready.
  16564. * @param {Function} func - the function to be executed.
  16565. */
  16566. Scene.prototype.executeWhenReady = function (func) {
  16567. var _this = this;
  16568. this.onReadyObservable.add(func);
  16569. if (this._executeWhenReadyTimeoutId !== -1) {
  16570. return;
  16571. }
  16572. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16573. _this._checkIsReady();
  16574. }, 150);
  16575. };
  16576. Scene.prototype._checkIsReady = function () {
  16577. var _this = this;
  16578. if (this.isReady()) {
  16579. this.onReadyObservable.notifyObservers(this);
  16580. this.onReadyObservable.clear();
  16581. this._executeWhenReadyTimeoutId = -1;
  16582. return;
  16583. }
  16584. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16585. _this._checkIsReady();
  16586. }, 150);
  16587. };
  16588. // Animations
  16589. /**
  16590. * Will start the animation sequence of a given target
  16591. * @param target - the target
  16592. * @param {number} from - from which frame should animation start
  16593. * @param {number} to - till which frame should animation run.
  16594. * @param {boolean} [loop] - should the animation loop
  16595. * @param {number} [speedRatio] - the speed in which to run the animation
  16596. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16597. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16598. * @return {BABYLON.Animatable} the animatable object created for this animation
  16599. * @see BABYLON.Animatable
  16600. * @see http://doc.babylonjs.com/page.php?p=22081
  16601. */
  16602. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16603. if (speedRatio === void 0) { speedRatio = 1.0; }
  16604. if (from > to && speedRatio > 0) {
  16605. speedRatio *= -1;
  16606. }
  16607. this.stopAnimation(target);
  16608. if (!animatable) {
  16609. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16610. }
  16611. // Local animations
  16612. if (target.animations) {
  16613. animatable.appendAnimations(target, target.animations);
  16614. }
  16615. // Children animations
  16616. if (target.getAnimatables) {
  16617. var animatables = target.getAnimatables();
  16618. for (var index = 0; index < animatables.length; index++) {
  16619. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16620. }
  16621. }
  16622. animatable.reset();
  16623. return animatable;
  16624. };
  16625. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16626. if (speedRatio === undefined) {
  16627. speedRatio = 1.0;
  16628. }
  16629. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16630. return animatable;
  16631. };
  16632. Scene.prototype.getAnimatableByTarget = function (target) {
  16633. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16634. if (this._activeAnimatables[index].target === target) {
  16635. return this._activeAnimatables[index];
  16636. }
  16637. }
  16638. return null;
  16639. };
  16640. Object.defineProperty(Scene.prototype, "Animatables", {
  16641. get: function () {
  16642. return this._activeAnimatables;
  16643. },
  16644. enumerable: true,
  16645. configurable: true
  16646. });
  16647. /**
  16648. * Will stop the animation of the given target
  16649. * @param target - the target
  16650. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16651. * @see beginAnimation
  16652. */
  16653. Scene.prototype.stopAnimation = function (target, animationName) {
  16654. var animatable = this.getAnimatableByTarget(target);
  16655. if (animatable) {
  16656. animatable.stop(animationName);
  16657. }
  16658. };
  16659. Scene.prototype._animate = function () {
  16660. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16661. return;
  16662. }
  16663. // Getting time
  16664. var now = BABYLON.Tools.Now;
  16665. if (!this._animationTimeLast) {
  16666. if (this._pendingData.length > 0) {
  16667. return;
  16668. }
  16669. this._animationTimeLast = now;
  16670. }
  16671. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16672. this._animationTime += deltaTime;
  16673. this._animationTimeLast = now;
  16674. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16675. this._activeAnimatables[index]._animate(this._animationTime);
  16676. }
  16677. };
  16678. // Matrix
  16679. Scene.prototype.getViewMatrix = function () {
  16680. return this._viewMatrix;
  16681. };
  16682. Scene.prototype.getProjectionMatrix = function () {
  16683. return this._projectionMatrix;
  16684. };
  16685. Scene.prototype.getTransformMatrix = function () {
  16686. return this._transformMatrix;
  16687. };
  16688. Scene.prototype.setTransformMatrix = function (view, projection) {
  16689. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16690. return;
  16691. }
  16692. this._viewUpdateFlag = view.updateFlag;
  16693. this._projectionUpdateFlag = projection.updateFlag;
  16694. this._viewMatrix = view;
  16695. this._projectionMatrix = projection;
  16696. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16697. // Update frustum
  16698. if (!this._frustumPlanes) {
  16699. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16700. }
  16701. else {
  16702. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16703. }
  16704. if (this._sceneUbo.useUbo) {
  16705. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16706. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16707. this._sceneUbo.update();
  16708. }
  16709. };
  16710. Scene.prototype.getSceneUniformBuffer = function () {
  16711. return this._sceneUbo;
  16712. };
  16713. // Methods
  16714. Scene.prototype.getUniqueId = function () {
  16715. var result = this._uniqueIdCounter;
  16716. this._uniqueIdCounter++;
  16717. return result;
  16718. };
  16719. Scene.prototype.addMesh = function (newMesh) {
  16720. newMesh.uniqueId = this.getUniqueId();
  16721. var position = this.meshes.push(newMesh);
  16722. //notify the collision coordinator
  16723. if (this.collisionCoordinator) {
  16724. this.collisionCoordinator.onMeshAdded(newMesh);
  16725. }
  16726. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16727. };
  16728. Scene.prototype.removeMesh = function (toRemove) {
  16729. var index = this.meshes.indexOf(toRemove);
  16730. if (index !== -1) {
  16731. // Remove from the scene if mesh found
  16732. this.meshes.splice(index, 1);
  16733. }
  16734. //notify the collision coordinator
  16735. if (this.collisionCoordinator) {
  16736. this.collisionCoordinator.onMeshRemoved(toRemove);
  16737. }
  16738. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16739. return index;
  16740. };
  16741. Scene.prototype.removeSkeleton = function (toRemove) {
  16742. var index = this.skeletons.indexOf(toRemove);
  16743. if (index !== -1) {
  16744. // Remove from the scene if found
  16745. this.skeletons.splice(index, 1);
  16746. }
  16747. return index;
  16748. };
  16749. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16750. var index = this.morphTargetManagers.indexOf(toRemove);
  16751. if (index !== -1) {
  16752. // Remove from the scene if found
  16753. this.morphTargetManagers.splice(index, 1);
  16754. }
  16755. return index;
  16756. };
  16757. Scene.prototype.removeLight = function (toRemove) {
  16758. var index = this.lights.indexOf(toRemove);
  16759. if (index !== -1) {
  16760. // Remove from the scene if mesh found
  16761. this.lights.splice(index, 1);
  16762. this.sortLightsByPriority();
  16763. }
  16764. this.onLightRemovedObservable.notifyObservers(toRemove);
  16765. return index;
  16766. };
  16767. Scene.prototype.removeCamera = function (toRemove) {
  16768. var index = this.cameras.indexOf(toRemove);
  16769. if (index !== -1) {
  16770. // Remove from the scene if mesh found
  16771. this.cameras.splice(index, 1);
  16772. }
  16773. // Remove from activeCameras
  16774. var index2 = this.activeCameras.indexOf(toRemove);
  16775. if (index2 !== -1) {
  16776. // Remove from the scene if mesh found
  16777. this.activeCameras.splice(index2, 1);
  16778. }
  16779. // Reset the activeCamera
  16780. if (this.activeCamera === toRemove) {
  16781. if (this.cameras.length > 0) {
  16782. this.activeCamera = this.cameras[0];
  16783. }
  16784. else {
  16785. this.activeCamera = null;
  16786. }
  16787. }
  16788. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16789. return index;
  16790. };
  16791. Scene.prototype.addLight = function (newLight) {
  16792. newLight.uniqueId = this.getUniqueId();
  16793. this.lights.push(newLight);
  16794. this.sortLightsByPriority();
  16795. this.onNewLightAddedObservable.notifyObservers(newLight);
  16796. };
  16797. Scene.prototype.sortLightsByPriority = function () {
  16798. if (this.requireLightSorting) {
  16799. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16800. }
  16801. };
  16802. Scene.prototype.addCamera = function (newCamera) {
  16803. newCamera.uniqueId = this.getUniqueId();
  16804. var position = this.cameras.push(newCamera);
  16805. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16806. };
  16807. /**
  16808. * Switch active camera
  16809. * @param {Camera} newCamera - new active camera
  16810. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16811. */
  16812. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16813. if (attachControl === void 0) { attachControl = true; }
  16814. var canvas = this._engine.getRenderingCanvas();
  16815. this.activeCamera.detachControl(canvas);
  16816. this.activeCamera = newCamera;
  16817. if (attachControl) {
  16818. newCamera.attachControl(canvas);
  16819. }
  16820. };
  16821. /**
  16822. * sets the active camera of the scene using its ID
  16823. * @param {string} id - the camera's ID
  16824. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16825. * @see activeCamera
  16826. */
  16827. Scene.prototype.setActiveCameraByID = function (id) {
  16828. var camera = this.getCameraByID(id);
  16829. if (camera) {
  16830. this.activeCamera = camera;
  16831. return camera;
  16832. }
  16833. return null;
  16834. };
  16835. /**
  16836. * sets the active camera of the scene using its name
  16837. * @param {string} name - the camera's name
  16838. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16839. * @see activeCamera
  16840. */
  16841. Scene.prototype.setActiveCameraByName = function (name) {
  16842. var camera = this.getCameraByName(name);
  16843. if (camera) {
  16844. this.activeCamera = camera;
  16845. return camera;
  16846. }
  16847. return null;
  16848. };
  16849. /**
  16850. * get a material using its id
  16851. * @param {string} the material's ID
  16852. * @return {BABYLON.Material|null} the material or null if none found.
  16853. */
  16854. Scene.prototype.getMaterialByID = function (id) {
  16855. for (var index = 0; index < this.materials.length; index++) {
  16856. if (this.materials[index].id === id) {
  16857. return this.materials[index];
  16858. }
  16859. }
  16860. return null;
  16861. };
  16862. /**
  16863. * get a material using its name
  16864. * @param {string} the material's name
  16865. * @return {BABYLON.Material|null} the material or null if none found.
  16866. */
  16867. Scene.prototype.getMaterialByName = function (name) {
  16868. for (var index = 0; index < this.materials.length; index++) {
  16869. if (this.materials[index].name === name) {
  16870. return this.materials[index];
  16871. }
  16872. }
  16873. return null;
  16874. };
  16875. Scene.prototype.getLensFlareSystemByName = function (name) {
  16876. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16877. if (this.lensFlareSystems[index].name === name) {
  16878. return this.lensFlareSystems[index];
  16879. }
  16880. }
  16881. return null;
  16882. };
  16883. Scene.prototype.getLensFlareSystemByID = function (id) {
  16884. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16885. if (this.lensFlareSystems[index].id === id) {
  16886. return this.lensFlareSystems[index];
  16887. }
  16888. }
  16889. return null;
  16890. };
  16891. Scene.prototype.getCameraByID = function (id) {
  16892. for (var index = 0; index < this.cameras.length; index++) {
  16893. if (this.cameras[index].id === id) {
  16894. return this.cameras[index];
  16895. }
  16896. }
  16897. return null;
  16898. };
  16899. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16900. for (var index = 0; index < this.cameras.length; index++) {
  16901. if (this.cameras[index].uniqueId === uniqueId) {
  16902. return this.cameras[index];
  16903. }
  16904. }
  16905. return null;
  16906. };
  16907. /**
  16908. * get a camera using its name
  16909. * @param {string} the camera's name
  16910. * @return {BABYLON.Camera|null} the camera or null if none found.
  16911. */
  16912. Scene.prototype.getCameraByName = function (name) {
  16913. for (var index = 0; index < this.cameras.length; index++) {
  16914. if (this.cameras[index].name === name) {
  16915. return this.cameras[index];
  16916. }
  16917. }
  16918. return null;
  16919. };
  16920. /**
  16921. * get a bone using its id
  16922. * @param {string} the bone's id
  16923. * @return {BABYLON.Bone|null} the bone or null if not found
  16924. */
  16925. Scene.prototype.getBoneByID = function (id) {
  16926. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16927. var skeleton = this.skeletons[skeletonIndex];
  16928. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16929. if (skeleton.bones[boneIndex].id === id) {
  16930. return skeleton.bones[boneIndex];
  16931. }
  16932. }
  16933. }
  16934. return null;
  16935. };
  16936. /**
  16937. * get a bone using its id
  16938. * @param {string} the bone's name
  16939. * @return {BABYLON.Bone|null} the bone or null if not found
  16940. */
  16941. Scene.prototype.getBoneByName = function (name) {
  16942. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16943. var skeleton = this.skeletons[skeletonIndex];
  16944. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16945. if (skeleton.bones[boneIndex].name === name) {
  16946. return skeleton.bones[boneIndex];
  16947. }
  16948. }
  16949. }
  16950. return null;
  16951. };
  16952. /**
  16953. * get a light node using its name
  16954. * @param {string} the light's name
  16955. * @return {BABYLON.Light|null} the light or null if none found.
  16956. */
  16957. Scene.prototype.getLightByName = function (name) {
  16958. for (var index = 0; index < this.lights.length; index++) {
  16959. if (this.lights[index].name === name) {
  16960. return this.lights[index];
  16961. }
  16962. }
  16963. return null;
  16964. };
  16965. /**
  16966. * get a light node using its ID
  16967. * @param {string} the light's id
  16968. * @return {BABYLON.Light|null} the light or null if none found.
  16969. */
  16970. Scene.prototype.getLightByID = function (id) {
  16971. for (var index = 0; index < this.lights.length; index++) {
  16972. if (this.lights[index].id === id) {
  16973. return this.lights[index];
  16974. }
  16975. }
  16976. return null;
  16977. };
  16978. /**
  16979. * get a light node using its scene-generated unique ID
  16980. * @param {number} the light's unique id
  16981. * @return {BABYLON.Light|null} the light or null if none found.
  16982. */
  16983. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16984. for (var index = 0; index < this.lights.length; index++) {
  16985. if (this.lights[index].uniqueId === uniqueId) {
  16986. return this.lights[index];
  16987. }
  16988. }
  16989. return null;
  16990. };
  16991. /**
  16992. * get a particle system by id
  16993. * @param id {number} the particle system id
  16994. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16995. */
  16996. Scene.prototype.getParticleSystemByID = function (id) {
  16997. for (var index = 0; index < this.particleSystems.length; index++) {
  16998. if (this.particleSystems[index].id === id) {
  16999. return this.particleSystems[index];
  17000. }
  17001. }
  17002. return null;
  17003. };
  17004. /**
  17005. * get a geometry using its ID
  17006. * @param {string} the geometry's id
  17007. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17008. */
  17009. Scene.prototype.getGeometryByID = function (id) {
  17010. for (var index = 0; index < this._geometries.length; index++) {
  17011. if (this._geometries[index].id === id) {
  17012. return this._geometries[index];
  17013. }
  17014. }
  17015. return null;
  17016. };
  17017. /**
  17018. * add a new geometry to this scene.
  17019. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17020. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17021. * @return {boolean} was the geometry added or not
  17022. */
  17023. Scene.prototype.pushGeometry = function (geometry, force) {
  17024. if (!force && this.getGeometryByID(geometry.id)) {
  17025. return false;
  17026. }
  17027. this._geometries.push(geometry);
  17028. //notify the collision coordinator
  17029. if (this.collisionCoordinator) {
  17030. this.collisionCoordinator.onGeometryAdded(geometry);
  17031. }
  17032. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17033. return true;
  17034. };
  17035. /**
  17036. * Removes an existing geometry
  17037. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17038. * @return {boolean} was the geometry removed or not
  17039. */
  17040. Scene.prototype.removeGeometry = function (geometry) {
  17041. var index = this._geometries.indexOf(geometry);
  17042. if (index > -1) {
  17043. this._geometries.splice(index, 1);
  17044. //notify the collision coordinator
  17045. if (this.collisionCoordinator) {
  17046. this.collisionCoordinator.onGeometryDeleted(geometry);
  17047. }
  17048. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17049. return true;
  17050. }
  17051. return false;
  17052. };
  17053. Scene.prototype.getGeometries = function () {
  17054. return this._geometries;
  17055. };
  17056. /**
  17057. * Get the first added mesh found of a given ID
  17058. * @param {string} id - the id to search for
  17059. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17060. */
  17061. Scene.prototype.getMeshByID = function (id) {
  17062. for (var index = 0; index < this.meshes.length; index++) {
  17063. if (this.meshes[index].id === id) {
  17064. return this.meshes[index];
  17065. }
  17066. }
  17067. return null;
  17068. };
  17069. Scene.prototype.getMeshesByID = function (id) {
  17070. return this.meshes.filter(function (m) {
  17071. return m.id === id;
  17072. });
  17073. };
  17074. /**
  17075. * Get a mesh with its auto-generated unique id
  17076. * @param {number} uniqueId - the unique id to search for
  17077. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17078. */
  17079. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17080. for (var index = 0; index < this.meshes.length; index++) {
  17081. if (this.meshes[index].uniqueId === uniqueId) {
  17082. return this.meshes[index];
  17083. }
  17084. }
  17085. return null;
  17086. };
  17087. /**
  17088. * Get a the last added mesh found of a given ID
  17089. * @param {string} id - the id to search for
  17090. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17091. */
  17092. Scene.prototype.getLastMeshByID = function (id) {
  17093. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17094. if (this.meshes[index].id === id) {
  17095. return this.meshes[index];
  17096. }
  17097. }
  17098. return null;
  17099. };
  17100. /**
  17101. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17102. * @param {string} id - the id to search for
  17103. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17104. */
  17105. Scene.prototype.getLastEntryByID = function (id) {
  17106. var index;
  17107. for (index = this.meshes.length - 1; index >= 0; index--) {
  17108. if (this.meshes[index].id === id) {
  17109. return this.meshes[index];
  17110. }
  17111. }
  17112. for (index = this.cameras.length - 1; index >= 0; index--) {
  17113. if (this.cameras[index].id === id) {
  17114. return this.cameras[index];
  17115. }
  17116. }
  17117. for (index = this.lights.length - 1; index >= 0; index--) {
  17118. if (this.lights[index].id === id) {
  17119. return this.lights[index];
  17120. }
  17121. }
  17122. return null;
  17123. };
  17124. Scene.prototype.getNodeByID = function (id) {
  17125. var mesh = this.getMeshByID(id);
  17126. if (mesh) {
  17127. return mesh;
  17128. }
  17129. var light = this.getLightByID(id);
  17130. if (light) {
  17131. return light;
  17132. }
  17133. var camera = this.getCameraByID(id);
  17134. if (camera) {
  17135. return camera;
  17136. }
  17137. var bone = this.getBoneByID(id);
  17138. return bone;
  17139. };
  17140. Scene.prototype.getNodeByName = function (name) {
  17141. var mesh = this.getMeshByName(name);
  17142. if (mesh) {
  17143. return mesh;
  17144. }
  17145. var light = this.getLightByName(name);
  17146. if (light) {
  17147. return light;
  17148. }
  17149. var camera = this.getCameraByName(name);
  17150. if (camera) {
  17151. return camera;
  17152. }
  17153. var bone = this.getBoneByName(name);
  17154. return bone;
  17155. };
  17156. Scene.prototype.getMeshByName = function (name) {
  17157. for (var index = 0; index < this.meshes.length; index++) {
  17158. if (this.meshes[index].name === name) {
  17159. return this.meshes[index];
  17160. }
  17161. }
  17162. return null;
  17163. };
  17164. Scene.prototype.getSoundByName = function (name) {
  17165. var index;
  17166. if (BABYLON.AudioEngine) {
  17167. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17168. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17169. return this.mainSoundTrack.soundCollection[index];
  17170. }
  17171. }
  17172. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17173. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17174. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17175. return this.soundTracks[sdIndex].soundCollection[index];
  17176. }
  17177. }
  17178. }
  17179. }
  17180. return null;
  17181. };
  17182. Scene.prototype.getLastSkeletonByID = function (id) {
  17183. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17184. if (this.skeletons[index].id === id) {
  17185. return this.skeletons[index];
  17186. }
  17187. }
  17188. return null;
  17189. };
  17190. Scene.prototype.getSkeletonById = function (id) {
  17191. for (var index = 0; index < this.skeletons.length; index++) {
  17192. if (this.skeletons[index].id === id) {
  17193. return this.skeletons[index];
  17194. }
  17195. }
  17196. return null;
  17197. };
  17198. Scene.prototype.getSkeletonByName = function (name) {
  17199. for (var index = 0; index < this.skeletons.length; index++) {
  17200. if (this.skeletons[index].name === name) {
  17201. return this.skeletons[index];
  17202. }
  17203. }
  17204. return null;
  17205. };
  17206. Scene.prototype.getMorphTargetManagerById = function (id) {
  17207. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17208. if (this.morphTargetManagers[index].uniqueId === id) {
  17209. return this.morphTargetManagers[index];
  17210. }
  17211. }
  17212. return null;
  17213. };
  17214. Scene.prototype.isActiveMesh = function (mesh) {
  17215. return (this._activeMeshes.indexOf(mesh) !== -1);
  17216. };
  17217. /**
  17218. * Return a the first highlight layer of the scene with a given name.
  17219. * @param name The name of the highlight layer to look for.
  17220. * @return The highlight layer if found otherwise null.
  17221. */
  17222. Scene.prototype.getHighlightLayerByName = function (name) {
  17223. for (var index = 0; index < this.highlightLayers.length; index++) {
  17224. if (this.highlightLayers[index].name === name) {
  17225. return this.highlightLayers[index];
  17226. }
  17227. }
  17228. return null;
  17229. };
  17230. Object.defineProperty(Scene.prototype, "uid", {
  17231. /**
  17232. * Return a unique id as a string which can serve as an identifier for the scene
  17233. */
  17234. get: function () {
  17235. if (!this._uid) {
  17236. this._uid = BABYLON.Tools.RandomId();
  17237. }
  17238. return this._uid;
  17239. },
  17240. enumerable: true,
  17241. configurable: true
  17242. });
  17243. /**
  17244. * Add an externaly attached data from its key.
  17245. * This method call will fail and return false, if such key already exists.
  17246. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17247. * @param key the unique key that identifies the data
  17248. * @param data the data object to associate to the key for this Engine instance
  17249. * @return true if no such key were already present and the data was added successfully, false otherwise
  17250. */
  17251. Scene.prototype.addExternalData = function (key, data) {
  17252. if (!this._externalData) {
  17253. this._externalData = new BABYLON.StringDictionary();
  17254. }
  17255. return this._externalData.add(key, data);
  17256. };
  17257. /**
  17258. * Get an externaly attached data from its key
  17259. * @param key the unique key that identifies the data
  17260. * @return the associated data, if present (can be null), or undefined if not present
  17261. */
  17262. Scene.prototype.getExternalData = function (key) {
  17263. if (!this._externalData) {
  17264. return null;
  17265. }
  17266. return this._externalData.get(key);
  17267. };
  17268. /**
  17269. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17270. * @param key the unique key that identifies the data
  17271. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17272. * @return the associated data, can be null if the factory returned null.
  17273. */
  17274. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17275. if (!this._externalData) {
  17276. this._externalData = new BABYLON.StringDictionary();
  17277. }
  17278. return this._externalData.getOrAddWithFactory(key, factory);
  17279. };
  17280. /**
  17281. * Remove an externaly attached data from the Engine instance
  17282. * @param key the unique key that identifies the data
  17283. * @return true if the data was successfully removed, false if it doesn't exist
  17284. */
  17285. Scene.prototype.removeExternalData = function (key) {
  17286. return this._externalData.remove(key);
  17287. };
  17288. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17289. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17290. var material = subMesh.getMaterial();
  17291. if (mesh.showSubMeshesBoundingBox) {
  17292. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17293. }
  17294. if (material) {
  17295. // Render targets
  17296. if (material.getRenderTargetTextures) {
  17297. if (this._processedMaterials.indexOf(material) === -1) {
  17298. this._processedMaterials.push(material);
  17299. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17300. }
  17301. }
  17302. // Dispatch
  17303. this._activeIndices.addCount(subMesh.indexCount, false);
  17304. this._renderingManager.dispatch(subMesh);
  17305. }
  17306. }
  17307. };
  17308. Scene.prototype._isInIntermediateRendering = function () {
  17309. return this._intermediateRendering;
  17310. };
  17311. Scene.prototype._evaluateActiveMeshes = function () {
  17312. this.activeCamera._activeMeshes.reset();
  17313. this._activeMeshes.reset();
  17314. this._renderingManager.reset();
  17315. this._processedMaterials.reset();
  17316. this._activeParticleSystems.reset();
  17317. this._activeSkeletons.reset();
  17318. this._softwareSkinnedMeshes.reset();
  17319. if (this._boundingBoxRenderer) {
  17320. this._boundingBoxRenderer.reset();
  17321. }
  17322. // Meshes
  17323. var meshes;
  17324. var len;
  17325. if (this._selectionOctree) {
  17326. var selection = this._selectionOctree.select(this._frustumPlanes);
  17327. meshes = selection.data;
  17328. len = selection.length;
  17329. }
  17330. else {
  17331. len = this.meshes.length;
  17332. meshes = this.meshes;
  17333. }
  17334. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17335. var mesh = meshes[meshIndex];
  17336. if (mesh.isBlocked) {
  17337. continue;
  17338. }
  17339. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17340. if (!mesh.isReady() || !mesh.isEnabled()) {
  17341. continue;
  17342. }
  17343. mesh.computeWorldMatrix();
  17344. // Intersections
  17345. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17346. this._meshesForIntersections.pushNoDuplicate(mesh);
  17347. }
  17348. // Switch to current LOD
  17349. var meshLOD = mesh.getLOD(this.activeCamera);
  17350. if (!meshLOD) {
  17351. continue;
  17352. }
  17353. mesh._preActivate();
  17354. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17355. this._activeMeshes.push(mesh);
  17356. this.activeCamera._activeMeshes.push(mesh);
  17357. mesh._activate(this._renderId);
  17358. this._activeMesh(mesh, meshLOD);
  17359. }
  17360. }
  17361. // Particle systems
  17362. this._particlesDuration.beginMonitoring();
  17363. var beforeParticlesDate = BABYLON.Tools.Now;
  17364. if (this.particlesEnabled) {
  17365. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17366. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17367. var particleSystem = this.particleSystems[particleIndex];
  17368. if (!particleSystem.isStarted()) {
  17369. continue;
  17370. }
  17371. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17372. this._activeParticleSystems.push(particleSystem);
  17373. particleSystem.animate();
  17374. this._renderingManager.dispatchParticles(particleSystem);
  17375. }
  17376. }
  17377. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17378. }
  17379. this._particlesDuration.endMonitoring(false);
  17380. };
  17381. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17382. if (mesh.skeleton && this.skeletonsEnabled) {
  17383. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17384. mesh.skeleton.prepare();
  17385. }
  17386. if (!mesh.computeBonesUsingShaders) {
  17387. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17388. }
  17389. }
  17390. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17391. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17392. }
  17393. if (mesh && mesh.subMeshes) {
  17394. // Submeshes Octrees
  17395. var len;
  17396. var subMeshes;
  17397. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17398. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17399. len = intersections.length;
  17400. subMeshes = intersections.data;
  17401. }
  17402. else {
  17403. subMeshes = mesh.subMeshes;
  17404. len = subMeshes.length;
  17405. }
  17406. for (var subIndex = 0; subIndex < len; subIndex++) {
  17407. var subMesh = subMeshes[subIndex];
  17408. this._evaluateSubMesh(subMesh, mesh);
  17409. }
  17410. }
  17411. };
  17412. Scene.prototype.updateTransformMatrix = function (force) {
  17413. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17414. };
  17415. Scene.prototype._renderForCamera = function (camera) {
  17416. var engine = this._engine;
  17417. var startTime = BABYLON.Tools.Now;
  17418. this.activeCamera = camera;
  17419. if (!this.activeCamera)
  17420. throw new Error("Active camera not set");
  17421. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17422. // Viewport
  17423. engine.setViewport(this.activeCamera.viewport);
  17424. // Camera
  17425. this.resetCachedMaterial();
  17426. this._renderId++;
  17427. this.updateTransformMatrix();
  17428. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17429. // Meshes
  17430. this._evaluateActiveMeshesDuration.beginMonitoring();
  17431. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17432. this._evaluateActiveMeshes();
  17433. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17434. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17435. // Software skinning
  17436. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17437. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17438. mesh.applySkeleton(mesh.skeleton);
  17439. }
  17440. // Render targets
  17441. this._renderTargetsDuration.beginMonitoring();
  17442. var needsRestoreFrameBuffer = false;
  17443. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17444. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17445. this._intermediateRendering = true;
  17446. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17447. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17448. var renderTarget = this._renderTargets.data[renderIndex];
  17449. if (renderTarget._shouldRender()) {
  17450. this._renderId++;
  17451. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17452. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17453. }
  17454. }
  17455. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17456. this._intermediateRendering = false;
  17457. this._renderId++;
  17458. needsRestoreFrameBuffer = true; // Restore back buffer
  17459. }
  17460. // Render HighlightLayer Texture
  17461. var stencilState = this._engine.getStencilBuffer();
  17462. var renderhighlights = false;
  17463. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17464. this._intermediateRendering = true;
  17465. for (var i = 0; i < this.highlightLayers.length; i++) {
  17466. var highlightLayer = this.highlightLayers[i];
  17467. if (highlightLayer.shouldRender() &&
  17468. (!highlightLayer.camera ||
  17469. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17470. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17471. renderhighlights = true;
  17472. var renderTarget = highlightLayer._mainTexture;
  17473. if (renderTarget._shouldRender()) {
  17474. this._renderId++;
  17475. renderTarget.render(false, false);
  17476. needsRestoreFrameBuffer = true;
  17477. }
  17478. }
  17479. }
  17480. this._intermediateRendering = false;
  17481. this._renderId++;
  17482. }
  17483. if (needsRestoreFrameBuffer) {
  17484. if (this.offscreenRenderTarget) {
  17485. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17486. }
  17487. else {
  17488. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17489. }
  17490. }
  17491. this._renderTargetsDuration.endMonitoring(false);
  17492. // Prepare Frame
  17493. this.postProcessManager._prepareFrame();
  17494. this._renderDuration.beginMonitoring();
  17495. // Backgrounds
  17496. var layerIndex;
  17497. var layer;
  17498. if (this.layers.length) {
  17499. engine.setDepthBuffer(false);
  17500. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17501. layer = this.layers[layerIndex];
  17502. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17503. layer.render();
  17504. }
  17505. }
  17506. engine.setDepthBuffer(true);
  17507. }
  17508. // Render
  17509. BABYLON.Tools.StartPerformanceCounter("Main render");
  17510. // Activate HighlightLayer stencil
  17511. if (renderhighlights) {
  17512. this._engine.setStencilBuffer(true);
  17513. }
  17514. this._renderingManager.render(null, null, true, true);
  17515. // Restore HighlightLayer stencil
  17516. if (renderhighlights) {
  17517. this._engine.setStencilBuffer(stencilState);
  17518. }
  17519. BABYLON.Tools.EndPerformanceCounter("Main render");
  17520. // Bounding boxes
  17521. if (this._boundingBoxRenderer) {
  17522. this._boundingBoxRenderer.render();
  17523. }
  17524. // Lens flares
  17525. if (this.lensFlaresEnabled) {
  17526. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17527. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17528. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17529. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17530. lensFlareSystem.render();
  17531. }
  17532. }
  17533. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17534. }
  17535. // Foregrounds
  17536. if (this.layers.length) {
  17537. engine.setDepthBuffer(false);
  17538. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17539. layer = this.layers[layerIndex];
  17540. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17541. layer.render();
  17542. }
  17543. }
  17544. engine.setDepthBuffer(true);
  17545. }
  17546. // Highlight Layer
  17547. if (renderhighlights) {
  17548. engine.setDepthBuffer(false);
  17549. for (var i = 0; i < this.highlightLayers.length; i++) {
  17550. if (this.highlightLayers[i].shouldRender()) {
  17551. this.highlightLayers[i].render();
  17552. }
  17553. }
  17554. engine.setDepthBuffer(true);
  17555. }
  17556. this._renderDuration.endMonitoring(false);
  17557. // Finalize frame
  17558. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17559. // Update camera
  17560. this.activeCamera._updateFromScene();
  17561. // Reset some special arrays
  17562. this._renderTargets.reset();
  17563. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17564. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17565. };
  17566. Scene.prototype._processSubCameras = function (camera) {
  17567. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17568. this._renderForCamera(camera);
  17569. return;
  17570. }
  17571. // rig cameras
  17572. for (var index = 0; index < camera._rigCameras.length; index++) {
  17573. this._renderForCamera(camera._rigCameras[index]);
  17574. }
  17575. this.activeCamera = camera;
  17576. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17577. // Update camera
  17578. this.activeCamera._updateFromScene();
  17579. };
  17580. Scene.prototype._checkIntersections = function () {
  17581. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17582. var sourceMesh = this._meshesForIntersections.data[index];
  17583. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17584. var action = sourceMesh.actionManager.actions[actionIndex];
  17585. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17586. var parameters = action.getTriggerParameter();
  17587. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17588. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17589. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17590. if (areIntersecting && currentIntersectionInProgress === -1) {
  17591. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17592. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17593. sourceMesh._intersectionsInProgress.push(otherMesh);
  17594. }
  17595. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17596. sourceMesh._intersectionsInProgress.push(otherMesh);
  17597. }
  17598. }
  17599. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17600. //They intersected, and now they don't.
  17601. //is this trigger an exit trigger? execute an event.
  17602. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17603. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17604. }
  17605. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17606. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17607. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17608. }
  17609. }
  17610. }
  17611. }
  17612. }
  17613. };
  17614. Scene.prototype.render = function () {
  17615. if (this.isDisposed) {
  17616. return;
  17617. }
  17618. this._lastFrameDuration.beginMonitoring();
  17619. this._particlesDuration.fetchNewFrame();
  17620. this._spritesDuration.fetchNewFrame();
  17621. this._activeParticles.fetchNewFrame();
  17622. this._renderDuration.fetchNewFrame();
  17623. this._renderTargetsDuration.fetchNewFrame();
  17624. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17625. this._totalVertices.fetchNewFrame();
  17626. this._activeIndices.fetchNewFrame();
  17627. this._activeBones.fetchNewFrame();
  17628. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17629. this._meshesForIntersections.reset();
  17630. this.resetCachedMaterial();
  17631. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17632. // Actions
  17633. if (this.actionManager) {
  17634. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17635. }
  17636. //Simplification Queue
  17637. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17638. this.simplificationQueue.executeNext();
  17639. }
  17640. // Animations
  17641. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17642. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17643. this._animate();
  17644. // Physics
  17645. if (this._physicsEngine) {
  17646. BABYLON.Tools.StartPerformanceCounter("Physics");
  17647. this._physicsEngine._step(deltaTime / 1000.0);
  17648. BABYLON.Tools.EndPerformanceCounter("Physics");
  17649. }
  17650. // Before render
  17651. this.onBeforeRenderObservable.notifyObservers(this);
  17652. // Customs render targets
  17653. this._renderTargetsDuration.beginMonitoring();
  17654. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17655. var engine = this.getEngine();
  17656. var currentActiveCamera = this.activeCamera;
  17657. if (this.renderTargetsEnabled) {
  17658. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17659. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17660. var renderTarget = this.customRenderTargets[customIndex];
  17661. if (renderTarget._shouldRender()) {
  17662. this._renderId++;
  17663. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17664. if (!this.activeCamera)
  17665. throw new Error("Active camera not set");
  17666. // Viewport
  17667. engine.setViewport(this.activeCamera.viewport);
  17668. // Camera
  17669. this.updateTransformMatrix();
  17670. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17671. }
  17672. }
  17673. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17674. this._renderId++;
  17675. }
  17676. if (this.offscreenRenderTarget) {
  17677. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17678. }
  17679. else {
  17680. // Restore back buffer
  17681. if (this.customRenderTargets.length > 0) {
  17682. engine.restoreDefaultFramebuffer();
  17683. }
  17684. }
  17685. this._renderTargetsDuration.endMonitoring();
  17686. this.activeCamera = currentActiveCamera;
  17687. // Procedural textures
  17688. if (this.proceduralTexturesEnabled) {
  17689. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17690. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17691. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17692. if (proceduralTexture._shouldRender()) {
  17693. proceduralTexture.render();
  17694. }
  17695. }
  17696. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17697. }
  17698. // Clear
  17699. if (this.autoClearDepthAndStencil || this.autoClear) {
  17700. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17701. }
  17702. // Shadows
  17703. if (this.shadowsEnabled) {
  17704. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17705. var light = this.lights[lightIndex];
  17706. var shadowGenerator = light.getShadowGenerator();
  17707. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17708. var shadowMap = shadowGenerator.getShadowMap();
  17709. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17710. this._renderTargets.push(shadowMap);
  17711. }
  17712. }
  17713. }
  17714. }
  17715. // Depth renderer
  17716. if (this._depthRenderer) {
  17717. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17718. }
  17719. // Geometry renderer
  17720. if (this._geometryBufferRenderer) {
  17721. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17722. }
  17723. // RenderPipeline
  17724. if (this._postProcessRenderPipelineManager) {
  17725. this._postProcessRenderPipelineManager.update();
  17726. }
  17727. // Multi-cameras?
  17728. if (this.activeCameras.length > 0) {
  17729. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17730. if (cameraIndex > 0) {
  17731. this._engine.clear(null, false, true, true);
  17732. }
  17733. this._processSubCameras(this.activeCameras[cameraIndex]);
  17734. }
  17735. }
  17736. else {
  17737. if (!this.activeCamera) {
  17738. throw new Error("No camera defined");
  17739. }
  17740. this._processSubCameras(this.activeCamera);
  17741. }
  17742. // Intersection checks
  17743. this._checkIntersections();
  17744. // Update the audio listener attached to the camera
  17745. if (BABYLON.AudioEngine) {
  17746. this._updateAudioParameters();
  17747. }
  17748. // After render
  17749. if (this.afterRender) {
  17750. this.afterRender();
  17751. }
  17752. this.onAfterRenderObservable.notifyObservers(this);
  17753. // Cleaning
  17754. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17755. this._toBeDisposed.data[index].dispose();
  17756. this._toBeDisposed[index] = null;
  17757. }
  17758. this._toBeDisposed.reset();
  17759. if (this.dumpNextRenderTargets) {
  17760. this.dumpNextRenderTargets = false;
  17761. }
  17762. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17763. this._lastFrameDuration.endMonitoring();
  17764. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17765. this._totalLightsCounter.addCount(this.lights.length, true);
  17766. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17767. this._totalTexturesCounter.addCount(this.textures.length, true);
  17768. this._activeBones.addCount(0, true);
  17769. this._activeIndices.addCount(0, true);
  17770. this._activeParticles.addCount(0, true);
  17771. };
  17772. Scene.prototype._updateAudioParameters = function () {
  17773. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17774. return;
  17775. }
  17776. var listeningCamera;
  17777. var audioEngine = BABYLON.Engine.audioEngine;
  17778. if (this.activeCameras.length > 0) {
  17779. listeningCamera = this.activeCameras[0];
  17780. }
  17781. else {
  17782. listeningCamera = this.activeCamera;
  17783. }
  17784. if (listeningCamera && audioEngine.canUseWebAudio) {
  17785. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17786. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17787. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17788. cameraDirection.normalize();
  17789. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17790. var i;
  17791. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17792. var sound = this.mainSoundTrack.soundCollection[i];
  17793. if (sound.useCustomAttenuation) {
  17794. sound.updateDistanceFromListener();
  17795. }
  17796. }
  17797. for (i = 0; i < this.soundTracks.length; i++) {
  17798. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17799. sound = this.soundTracks[i].soundCollection[j];
  17800. if (sound.useCustomAttenuation) {
  17801. sound.updateDistanceFromListener();
  17802. }
  17803. }
  17804. }
  17805. }
  17806. };
  17807. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17808. // Audio
  17809. get: function () {
  17810. return this._audioEnabled;
  17811. },
  17812. set: function (value) {
  17813. this._audioEnabled = value;
  17814. if (BABYLON.AudioEngine) {
  17815. if (this._audioEnabled) {
  17816. this._enableAudio();
  17817. }
  17818. else {
  17819. this._disableAudio();
  17820. }
  17821. }
  17822. },
  17823. enumerable: true,
  17824. configurable: true
  17825. });
  17826. Scene.prototype._disableAudio = function () {
  17827. var i;
  17828. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17829. this.mainSoundTrack.soundCollection[i].pause();
  17830. }
  17831. for (i = 0; i < this.soundTracks.length; i++) {
  17832. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17833. this.soundTracks[i].soundCollection[j].pause();
  17834. }
  17835. }
  17836. };
  17837. Scene.prototype._enableAudio = function () {
  17838. var i;
  17839. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17840. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17841. this.mainSoundTrack.soundCollection[i].play();
  17842. }
  17843. }
  17844. for (i = 0; i < this.soundTracks.length; i++) {
  17845. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17846. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17847. this.soundTracks[i].soundCollection[j].play();
  17848. }
  17849. }
  17850. }
  17851. };
  17852. Object.defineProperty(Scene.prototype, "headphone", {
  17853. get: function () {
  17854. return this._headphone;
  17855. },
  17856. set: function (value) {
  17857. this._headphone = value;
  17858. if (BABYLON.AudioEngine) {
  17859. if (this._headphone) {
  17860. this._switchAudioModeForHeadphones();
  17861. }
  17862. else {
  17863. this._switchAudioModeForNormalSpeakers();
  17864. }
  17865. }
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. Scene.prototype._switchAudioModeForHeadphones = function () {
  17871. this.mainSoundTrack.switchPanningModelToHRTF();
  17872. for (var i = 0; i < this.soundTracks.length; i++) {
  17873. this.soundTracks[i].switchPanningModelToHRTF();
  17874. }
  17875. };
  17876. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17877. this.mainSoundTrack.switchPanningModelToEqualPower();
  17878. for (var i = 0; i < this.soundTracks.length; i++) {
  17879. this.soundTracks[i].switchPanningModelToEqualPower();
  17880. }
  17881. };
  17882. Scene.prototype.enableDepthRenderer = function () {
  17883. if (this._depthRenderer) {
  17884. return this._depthRenderer;
  17885. }
  17886. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17887. return this._depthRenderer;
  17888. };
  17889. Scene.prototype.disableDepthRenderer = function () {
  17890. if (!this._depthRenderer) {
  17891. return;
  17892. }
  17893. this._depthRenderer.dispose();
  17894. this._depthRenderer = null;
  17895. };
  17896. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17897. if (ratio === void 0) { ratio = 1; }
  17898. if (this._geometryBufferRenderer) {
  17899. return this._geometryBufferRenderer;
  17900. }
  17901. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17902. if (!this._geometryBufferRenderer.isSupported) {
  17903. this._geometryBufferRenderer = null;
  17904. }
  17905. return this._geometryBufferRenderer;
  17906. };
  17907. Scene.prototype.disableGeometryBufferRenderer = function () {
  17908. if (!this._geometryBufferRenderer) {
  17909. return;
  17910. }
  17911. this._geometryBufferRenderer.dispose();
  17912. this._geometryBufferRenderer = null;
  17913. };
  17914. Scene.prototype.freezeMaterials = function () {
  17915. for (var i = 0; i < this.materials.length; i++) {
  17916. this.materials[i].freeze();
  17917. }
  17918. };
  17919. Scene.prototype.unfreezeMaterials = function () {
  17920. for (var i = 0; i < this.materials.length; i++) {
  17921. this.materials[i].unfreeze();
  17922. }
  17923. };
  17924. Scene.prototype.dispose = function () {
  17925. this.beforeRender = null;
  17926. this.afterRender = null;
  17927. this.skeletons = [];
  17928. this.morphTargetManagers = [];
  17929. this.importedMeshesFiles = new Array();
  17930. if (this._depthRenderer) {
  17931. this._depthRenderer.dispose();
  17932. }
  17933. // Smart arrays
  17934. if (this.activeCamera) {
  17935. this.activeCamera._activeMeshes.dispose();
  17936. this.activeCamera = null;
  17937. }
  17938. this._activeMeshes.dispose();
  17939. this._renderingManager.dispose();
  17940. this._processedMaterials.dispose();
  17941. this._activeParticleSystems.dispose();
  17942. this._activeSkeletons.dispose();
  17943. this._softwareSkinnedMeshes.dispose();
  17944. if (this._boundingBoxRenderer) {
  17945. this._boundingBoxRenderer.dispose();
  17946. }
  17947. this._meshesForIntersections.dispose();
  17948. this._toBeDisposed.dispose();
  17949. // Debug layer
  17950. if (this._debugLayer) {
  17951. this._debugLayer.hide();
  17952. }
  17953. // Events
  17954. this.onDisposeObservable.notifyObservers(this);
  17955. this.onDisposeObservable.clear();
  17956. this.onBeforeRenderObservable.clear();
  17957. this.onAfterRenderObservable.clear();
  17958. this.detachControl();
  17959. // Release sounds & sounds tracks
  17960. if (BABYLON.AudioEngine) {
  17961. this.disposeSounds();
  17962. }
  17963. // Detach cameras
  17964. var canvas = this._engine.getRenderingCanvas();
  17965. var index;
  17966. for (index = 0; index < this.cameras.length; index++) {
  17967. this.cameras[index].detachControl(canvas);
  17968. }
  17969. // Release lights
  17970. while (this.lights.length) {
  17971. this.lights[0].dispose();
  17972. }
  17973. // Release meshes
  17974. while (this.meshes.length) {
  17975. this.meshes[0].dispose(true);
  17976. }
  17977. // Release cameras
  17978. while (this.cameras.length) {
  17979. this.cameras[0].dispose();
  17980. }
  17981. // Release materials
  17982. while (this.materials.length) {
  17983. this.materials[0].dispose();
  17984. }
  17985. // Release particles
  17986. while (this.particleSystems.length) {
  17987. this.particleSystems[0].dispose();
  17988. }
  17989. // Release sprites
  17990. while (this.spriteManagers.length) {
  17991. this.spriteManagers[0].dispose();
  17992. }
  17993. // Release layers
  17994. while (this.layers.length) {
  17995. this.layers[0].dispose();
  17996. }
  17997. while (this.highlightLayers.length) {
  17998. this.highlightLayers[0].dispose();
  17999. }
  18000. // Release textures
  18001. while (this.textures.length) {
  18002. this.textures[0].dispose();
  18003. }
  18004. // Release UBO
  18005. this._sceneUbo.dispose();
  18006. // Post-processes
  18007. this.postProcessManager.dispose();
  18008. // Physics
  18009. if (this._physicsEngine) {
  18010. this.disablePhysicsEngine();
  18011. }
  18012. // Remove from engine
  18013. index = this._engine.scenes.indexOf(this);
  18014. if (index > -1) {
  18015. this._engine.scenes.splice(index, 1);
  18016. }
  18017. this._engine.wipeCaches();
  18018. this._engine = null;
  18019. };
  18020. Object.defineProperty(Scene.prototype, "isDisposed", {
  18021. get: function () {
  18022. return !this._engine;
  18023. },
  18024. enumerable: true,
  18025. configurable: true
  18026. });
  18027. // Release sounds & sounds tracks
  18028. Scene.prototype.disposeSounds = function () {
  18029. this.mainSoundTrack.dispose();
  18030. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18031. this.soundTracks[scIndex].dispose();
  18032. }
  18033. };
  18034. // Octrees
  18035. Scene.prototype.getWorldExtends = function () {
  18036. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18037. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18038. for (var index = 0; index < this.meshes.length; index++) {
  18039. var mesh = this.meshes[index];
  18040. mesh.computeWorldMatrix(true);
  18041. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18042. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18043. BABYLON.Tools.CheckExtends(minBox, min, max);
  18044. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18045. }
  18046. return {
  18047. min: min,
  18048. max: max
  18049. };
  18050. };
  18051. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18052. if (maxCapacity === void 0) { maxCapacity = 64; }
  18053. if (maxDepth === void 0) { maxDepth = 2; }
  18054. if (!this._selectionOctree) {
  18055. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18056. }
  18057. var worldExtends = this.getWorldExtends();
  18058. // Update octree
  18059. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18060. return this._selectionOctree;
  18061. };
  18062. // Picking
  18063. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18064. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18065. var engine = this._engine;
  18066. if (!camera) {
  18067. if (!this.activeCamera)
  18068. throw new Error("Active camera not set");
  18069. camera = this.activeCamera;
  18070. }
  18071. var cameraViewport = camera.viewport;
  18072. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18073. // Moving coordinates to local viewport world
  18074. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18075. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18076. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18077. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18078. };
  18079. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18080. if (!BABYLON.PickingInfo) {
  18081. return null;
  18082. }
  18083. var engine = this._engine;
  18084. if (!camera) {
  18085. if (!this.activeCamera)
  18086. throw new Error("Active camera not set");
  18087. camera = this.activeCamera;
  18088. }
  18089. var cameraViewport = camera.viewport;
  18090. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18091. var identity = BABYLON.Matrix.Identity();
  18092. // Moving coordinates to local viewport world
  18093. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18094. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18095. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18096. };
  18097. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18098. if (!BABYLON.PickingInfo) {
  18099. return null;
  18100. }
  18101. var pickingInfo = null;
  18102. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18103. var mesh = this.meshes[meshIndex];
  18104. if (predicate) {
  18105. if (!predicate(mesh)) {
  18106. continue;
  18107. }
  18108. }
  18109. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18110. continue;
  18111. }
  18112. var world = mesh.getWorldMatrix();
  18113. var ray = rayFunction(world);
  18114. var result = mesh.intersects(ray, fastCheck);
  18115. if (!result || !result.hit)
  18116. continue;
  18117. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18118. continue;
  18119. pickingInfo = result;
  18120. if (fastCheck) {
  18121. break;
  18122. }
  18123. }
  18124. return pickingInfo || new BABYLON.PickingInfo();
  18125. };
  18126. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18127. if (!BABYLON.PickingInfo) {
  18128. return null;
  18129. }
  18130. var pickingInfos = new Array();
  18131. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18132. var mesh = this.meshes[meshIndex];
  18133. if (predicate) {
  18134. if (!predicate(mesh)) {
  18135. continue;
  18136. }
  18137. }
  18138. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18139. continue;
  18140. }
  18141. var world = mesh.getWorldMatrix();
  18142. var ray = rayFunction(world);
  18143. var result = mesh.intersects(ray, false);
  18144. if (!result || !result.hit)
  18145. continue;
  18146. pickingInfos.push(result);
  18147. }
  18148. return pickingInfos;
  18149. };
  18150. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18151. if (!BABYLON.PickingInfo) {
  18152. return null;
  18153. }
  18154. var pickingInfo = null;
  18155. camera = camera || this.activeCamera;
  18156. if (this.spriteManagers.length > 0) {
  18157. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18158. var spriteManager = this.spriteManagers[spriteIndex];
  18159. if (!spriteManager.isPickable) {
  18160. continue;
  18161. }
  18162. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18163. if (!result || !result.hit)
  18164. continue;
  18165. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18166. continue;
  18167. pickingInfo = result;
  18168. if (fastCheck) {
  18169. break;
  18170. }
  18171. }
  18172. }
  18173. return pickingInfo || new BABYLON.PickingInfo();
  18174. };
  18175. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18176. /// <param name="x">X position on screen</param>
  18177. /// <param name="y">Y position on screen</param>
  18178. /// <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>
  18179. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18180. /// <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>
  18181. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18182. var _this = this;
  18183. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18184. };
  18185. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18186. /// <param name="x">X position on screen</param>
  18187. /// <param name="y">Y position on screen</param>
  18188. /// <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>
  18189. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18190. /// <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>
  18191. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18192. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18193. };
  18194. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18195. var _this = this;
  18196. return this._internalPick(function (world) {
  18197. if (!_this._pickWithRayInverseMatrix) {
  18198. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18199. }
  18200. world.invertToRef(_this._pickWithRayInverseMatrix);
  18201. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18202. }, predicate, fastCheck);
  18203. };
  18204. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18205. /// <param name="x">X position on screen</param>
  18206. /// <param name="y">Y position on screen</param>
  18207. /// <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>
  18208. /// <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>
  18209. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18210. var _this = this;
  18211. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18212. };
  18213. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18214. /// <param name="ray">Ray to use</param>
  18215. /// <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>
  18216. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18217. var _this = this;
  18218. return this._internalMultiPick(function (world) {
  18219. if (!_this._pickWithRayInverseMatrix) {
  18220. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18221. }
  18222. world.invertToRef(_this._pickWithRayInverseMatrix);
  18223. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18224. }, predicate);
  18225. };
  18226. Scene.prototype.setPointerOverMesh = function (mesh) {
  18227. if (this._pointerOverMesh === mesh) {
  18228. return;
  18229. }
  18230. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18231. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18232. }
  18233. this._pointerOverMesh = mesh;
  18234. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18235. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18236. }
  18237. };
  18238. Scene.prototype.getPointerOverMesh = function () {
  18239. return this._pointerOverMesh;
  18240. };
  18241. Scene.prototype.setPointerOverSprite = function (sprite) {
  18242. if (this._pointerOverSprite === sprite) {
  18243. return;
  18244. }
  18245. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18246. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18247. }
  18248. this._pointerOverSprite = sprite;
  18249. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18250. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18251. }
  18252. };
  18253. Scene.prototype.getPointerOverSprite = function () {
  18254. return this._pointerOverSprite;
  18255. };
  18256. // Physics
  18257. Scene.prototype.getPhysicsEngine = function () {
  18258. return this._physicsEngine;
  18259. };
  18260. /**
  18261. * Enables physics to the current scene
  18262. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18263. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18264. * @return {boolean} was the physics engine initialized
  18265. */
  18266. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18267. if (this._physicsEngine) {
  18268. return true;
  18269. }
  18270. try {
  18271. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18272. return true;
  18273. }
  18274. catch (e) {
  18275. BABYLON.Tools.Error(e.message);
  18276. return false;
  18277. }
  18278. };
  18279. Scene.prototype.disablePhysicsEngine = function () {
  18280. if (!this._physicsEngine) {
  18281. return;
  18282. }
  18283. this._physicsEngine.dispose();
  18284. this._physicsEngine = undefined;
  18285. };
  18286. Scene.prototype.isPhysicsEnabled = function () {
  18287. return this._physicsEngine !== undefined;
  18288. };
  18289. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18290. var mesh = compound.parts[0].mesh;
  18291. mesh.physicsImpostor.dispose();
  18292. mesh.physicsImpostor = null;
  18293. };
  18294. // Misc.
  18295. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18296. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18297. // Light
  18298. if (this.lights.length === 0) {
  18299. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18300. }
  18301. // Camera
  18302. if (!this.activeCamera) {
  18303. var worldExtends = this.getWorldExtends();
  18304. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18305. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18306. var camera;
  18307. var radius = worldSize.length() * 1.5;
  18308. if (createArcRotateCamera) {
  18309. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18310. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18311. arcRotateCamera.wheelPrecision = 100 / radius;
  18312. camera = arcRotateCamera;
  18313. }
  18314. else {
  18315. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18316. freeCamera.setTarget(worldCenter);
  18317. camera = freeCamera;
  18318. }
  18319. camera.minZ = radius * 0.01;
  18320. camera.maxZ = radius * 100;
  18321. camera.speed = radius * 0.2;
  18322. this.activeCamera = camera;
  18323. }
  18324. };
  18325. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18326. if (pbr === void 0) { pbr = false; }
  18327. if (environmentTexture) {
  18328. this.environmentTexture = environmentTexture;
  18329. }
  18330. if (!this.environmentTexture) {
  18331. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18332. return;
  18333. }
  18334. if (!this.environmentTexture) {
  18335. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18336. return;
  18337. }
  18338. // Skybox
  18339. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18340. if (pbr) {
  18341. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18342. hdrSkyboxMaterial.backFaceCulling = false;
  18343. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18344. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18345. hdrSkyboxMaterial.microSurface = 1.0;
  18346. hdrSkyboxMaterial.disableLighting = true;
  18347. hdrSkybox.infiniteDistance = true;
  18348. hdrSkybox.material = hdrSkyboxMaterial;
  18349. }
  18350. else {
  18351. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18352. skyboxMaterial.backFaceCulling = false;
  18353. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18354. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18355. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18356. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18357. skyboxMaterial.disableLighting = true;
  18358. hdrSkybox.infiniteDistance = true;
  18359. hdrSkybox.material = skyboxMaterial;
  18360. }
  18361. return hdrSkybox;
  18362. };
  18363. // Tags
  18364. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18365. if (tagsQuery === undefined) {
  18366. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18367. return list;
  18368. }
  18369. var listByTags = [];
  18370. forEach = forEach || (function (item) { return; });
  18371. for (var i in list) {
  18372. var item = list[i];
  18373. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18374. listByTags.push(item);
  18375. forEach(item);
  18376. }
  18377. }
  18378. return listByTags;
  18379. };
  18380. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18381. return this._getByTags(this.meshes, tagsQuery, forEach);
  18382. };
  18383. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18384. return this._getByTags(this.cameras, tagsQuery, forEach);
  18385. };
  18386. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18387. return this._getByTags(this.lights, tagsQuery, forEach);
  18388. };
  18389. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18390. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18391. };
  18392. /**
  18393. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18394. * This allowed control for front to back rendering or reversly depending of the special needs.
  18395. *
  18396. * @param renderingGroupId The rendering group id corresponding to its index
  18397. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18398. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18399. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18400. */
  18401. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18402. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18403. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18404. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18405. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18406. };
  18407. /**
  18408. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18409. *
  18410. * @param renderingGroupId The rendering group id corresponding to its index
  18411. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18412. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18413. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18414. */
  18415. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18416. if (depth === void 0) { depth = true; }
  18417. if (stencil === void 0) { stencil = true; }
  18418. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18419. };
  18420. /**
  18421. * Will flag all materials as dirty to trigger new shader compilation
  18422. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18423. */
  18424. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18425. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18426. var material = _a[_i];
  18427. if (predicate && !predicate(material)) {
  18428. continue;
  18429. }
  18430. material.markAsDirty(flag);
  18431. }
  18432. };
  18433. return Scene;
  18434. }());
  18435. // Statics
  18436. Scene._FOGMODE_NONE = 0;
  18437. Scene._FOGMODE_EXP = 1;
  18438. Scene._FOGMODE_EXP2 = 2;
  18439. Scene._FOGMODE_LINEAR = 3;
  18440. Scene.MinDeltaTime = 1.0;
  18441. Scene.MaxDeltaTime = 1000.0;
  18442. Scene.DragMovementThreshold = 10; // in pixels
  18443. Scene.LongPressDelay = 500; // in milliseconds
  18444. Scene.DoubleClickDelay = 300; // in milliseconds
  18445. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18446. BABYLON.Scene = Scene;
  18447. })(BABYLON || (BABYLON = {}));
  18448. //# sourceMappingURL=babylon.scene.js.map
  18449. var BABYLON;
  18450. (function (BABYLON) {
  18451. var Buffer = (function () {
  18452. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18453. if (engine instanceof BABYLON.Mesh) {
  18454. this._engine = engine.getScene().getEngine();
  18455. }
  18456. else {
  18457. this._engine = engine;
  18458. }
  18459. this._updatable = updatable;
  18460. this._data = data;
  18461. this._strideSize = stride;
  18462. if (!postponeInternalCreation) {
  18463. this.create();
  18464. }
  18465. this._instanced = instanced;
  18466. }
  18467. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18468. // a lot of these parameters are ignored as they are overriden by the buffer
  18469. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18470. };
  18471. // Properties
  18472. Buffer.prototype.isUpdatable = function () {
  18473. return this._updatable;
  18474. };
  18475. Buffer.prototype.getData = function () {
  18476. return this._data;
  18477. };
  18478. Buffer.prototype.getBuffer = function () {
  18479. return this._buffer;
  18480. };
  18481. Buffer.prototype.getStrideSize = function () {
  18482. return this._strideSize;
  18483. };
  18484. Buffer.prototype.getIsInstanced = function () {
  18485. return this._instanced;
  18486. };
  18487. // Methods
  18488. Buffer.prototype.create = function (data) {
  18489. if (!data && this._buffer) {
  18490. return; // nothing to do
  18491. }
  18492. data = data || this._data;
  18493. if (!this._buffer) {
  18494. if (this._updatable) {
  18495. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18496. this._data = data;
  18497. }
  18498. else {
  18499. this._buffer = this._engine.createVertexBuffer(data);
  18500. }
  18501. }
  18502. else if (this._updatable) {
  18503. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18504. this._data = data;
  18505. }
  18506. };
  18507. Buffer.prototype.update = function (data) {
  18508. this.create(data);
  18509. };
  18510. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18511. if (!this._buffer) {
  18512. return;
  18513. }
  18514. if (this._updatable) {
  18515. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18516. this._data = null;
  18517. }
  18518. };
  18519. Buffer.prototype.dispose = function () {
  18520. if (!this._buffer) {
  18521. return;
  18522. }
  18523. if (this._engine._releaseBuffer(this._buffer)) {
  18524. this._buffer = null;
  18525. }
  18526. };
  18527. return Buffer;
  18528. }());
  18529. BABYLON.Buffer = Buffer;
  18530. })(BABYLON || (BABYLON = {}));
  18531. //# sourceMappingURL=babylon.buffer.js.map
  18532. var BABYLON;
  18533. (function (BABYLON) {
  18534. var VertexBuffer = (function () {
  18535. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18536. if (!stride) {
  18537. // Deduce stride from kind
  18538. switch (kind) {
  18539. case VertexBuffer.PositionKind:
  18540. stride = 3;
  18541. break;
  18542. case VertexBuffer.NormalKind:
  18543. stride = 3;
  18544. break;
  18545. case VertexBuffer.UVKind:
  18546. case VertexBuffer.UV2Kind:
  18547. case VertexBuffer.UV3Kind:
  18548. case VertexBuffer.UV4Kind:
  18549. case VertexBuffer.UV5Kind:
  18550. case VertexBuffer.UV6Kind:
  18551. stride = 2;
  18552. break;
  18553. case VertexBuffer.TangentKind:
  18554. case VertexBuffer.ColorKind:
  18555. stride = 4;
  18556. break;
  18557. case VertexBuffer.MatricesIndicesKind:
  18558. case VertexBuffer.MatricesIndicesExtraKind:
  18559. stride = 4;
  18560. break;
  18561. case VertexBuffer.MatricesWeightsKind:
  18562. case VertexBuffer.MatricesWeightsExtraKind:
  18563. stride = 4;
  18564. break;
  18565. }
  18566. }
  18567. if (data instanceof BABYLON.Buffer) {
  18568. if (!stride) {
  18569. stride = data.getStrideSize();
  18570. }
  18571. this._buffer = data;
  18572. this._ownsBuffer = false;
  18573. }
  18574. else {
  18575. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18576. this._ownsBuffer = true;
  18577. }
  18578. this._stride = stride;
  18579. this._offset = offset ? offset : 0;
  18580. this._size = size ? size : stride;
  18581. this._kind = kind;
  18582. }
  18583. /**
  18584. * Returns the kind of the VertexBuffer (string).
  18585. */
  18586. VertexBuffer.prototype.getKind = function () {
  18587. return this._kind;
  18588. };
  18589. // Properties
  18590. /**
  18591. * Boolean : is the VertexBuffer updatable ?
  18592. */
  18593. VertexBuffer.prototype.isUpdatable = function () {
  18594. return this._buffer.isUpdatable();
  18595. };
  18596. /**
  18597. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18598. */
  18599. VertexBuffer.prototype.getData = function () {
  18600. return this._buffer.getData();
  18601. };
  18602. /**
  18603. * Returns the WebGLBuffer associated to the VertexBuffer.
  18604. */
  18605. VertexBuffer.prototype.getBuffer = function () {
  18606. return this._buffer.getBuffer();
  18607. };
  18608. /**
  18609. * Returns the stride of the VertexBuffer (integer).
  18610. */
  18611. VertexBuffer.prototype.getStrideSize = function () {
  18612. return this._stride;
  18613. };
  18614. /**
  18615. * Returns the offset (integer).
  18616. */
  18617. VertexBuffer.prototype.getOffset = function () {
  18618. return this._offset;
  18619. };
  18620. /**
  18621. * Returns the VertexBuffer total size (integer).
  18622. */
  18623. VertexBuffer.prototype.getSize = function () {
  18624. return this._size;
  18625. };
  18626. /**
  18627. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18628. */
  18629. VertexBuffer.prototype.getIsInstanced = function () {
  18630. return this._buffer.getIsInstanced();
  18631. };
  18632. // Methods
  18633. /**
  18634. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18635. * Returns the created WebGLBuffer.
  18636. */
  18637. VertexBuffer.prototype.create = function (data) {
  18638. return this._buffer.create(data);
  18639. };
  18640. /**
  18641. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18642. * Returns the updated WebGLBuffer.
  18643. */
  18644. VertexBuffer.prototype.update = function (data) {
  18645. return this._buffer.update(data);
  18646. };
  18647. /**
  18648. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18649. * Returns the directly updated WebGLBuffer.
  18650. */
  18651. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18652. return this._buffer.updateDirectly(data, offset);
  18653. };
  18654. /**
  18655. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18656. */
  18657. VertexBuffer.prototype.dispose = function () {
  18658. if (this._ownsBuffer) {
  18659. this._buffer.dispose();
  18660. }
  18661. };
  18662. Object.defineProperty(VertexBuffer, "PositionKind", {
  18663. get: function () {
  18664. return VertexBuffer._PositionKind;
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. Object.defineProperty(VertexBuffer, "NormalKind", {
  18670. get: function () {
  18671. return VertexBuffer._NormalKind;
  18672. },
  18673. enumerable: true,
  18674. configurable: true
  18675. });
  18676. Object.defineProperty(VertexBuffer, "TangentKind", {
  18677. get: function () {
  18678. return VertexBuffer._TangentKind;
  18679. },
  18680. enumerable: true,
  18681. configurable: true
  18682. });
  18683. Object.defineProperty(VertexBuffer, "UVKind", {
  18684. get: function () {
  18685. return VertexBuffer._UVKind;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18691. get: function () {
  18692. return VertexBuffer._UV2Kind;
  18693. },
  18694. enumerable: true,
  18695. configurable: true
  18696. });
  18697. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18698. get: function () {
  18699. return VertexBuffer._UV3Kind;
  18700. },
  18701. enumerable: true,
  18702. configurable: true
  18703. });
  18704. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18705. get: function () {
  18706. return VertexBuffer._UV4Kind;
  18707. },
  18708. enumerable: true,
  18709. configurable: true
  18710. });
  18711. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18712. get: function () {
  18713. return VertexBuffer._UV5Kind;
  18714. },
  18715. enumerable: true,
  18716. configurable: true
  18717. });
  18718. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18719. get: function () {
  18720. return VertexBuffer._UV6Kind;
  18721. },
  18722. enumerable: true,
  18723. configurable: true
  18724. });
  18725. Object.defineProperty(VertexBuffer, "ColorKind", {
  18726. get: function () {
  18727. return VertexBuffer._ColorKind;
  18728. },
  18729. enumerable: true,
  18730. configurable: true
  18731. });
  18732. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18733. get: function () {
  18734. return VertexBuffer._MatricesIndicesKind;
  18735. },
  18736. enumerable: true,
  18737. configurable: true
  18738. });
  18739. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18740. get: function () {
  18741. return VertexBuffer._MatricesWeightsKind;
  18742. },
  18743. enumerable: true,
  18744. configurable: true
  18745. });
  18746. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18747. get: function () {
  18748. return VertexBuffer._MatricesIndicesExtraKind;
  18749. },
  18750. enumerable: true,
  18751. configurable: true
  18752. });
  18753. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18754. get: function () {
  18755. return VertexBuffer._MatricesWeightsExtraKind;
  18756. },
  18757. enumerable: true,
  18758. configurable: true
  18759. });
  18760. return VertexBuffer;
  18761. }());
  18762. // Enums
  18763. VertexBuffer._PositionKind = "position";
  18764. VertexBuffer._NormalKind = "normal";
  18765. VertexBuffer._TangentKind = "tangent";
  18766. VertexBuffer._UVKind = "uv";
  18767. VertexBuffer._UV2Kind = "uv2";
  18768. VertexBuffer._UV3Kind = "uv3";
  18769. VertexBuffer._UV4Kind = "uv4";
  18770. VertexBuffer._UV5Kind = "uv5";
  18771. VertexBuffer._UV6Kind = "uv6";
  18772. VertexBuffer._ColorKind = "color";
  18773. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18774. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18775. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18776. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18777. BABYLON.VertexBuffer = VertexBuffer;
  18778. })(BABYLON || (BABYLON = {}));
  18779. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18780. var BABYLON;
  18781. (function (BABYLON) {
  18782. var BaseTexture = (function () {
  18783. function BaseTexture(scene) {
  18784. this._hasAlpha = false;
  18785. this.getAlphaFromRGB = false;
  18786. this.level = 1;
  18787. this.coordinatesIndex = 0;
  18788. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18789. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18790. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18791. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18792. this.isCube = false;
  18793. this.isRenderTarget = false;
  18794. this.animations = new Array();
  18795. /**
  18796. * An event triggered when the texture is disposed.
  18797. * @type {BABYLON.Observable}
  18798. */
  18799. this.onDisposeObservable = new BABYLON.Observable();
  18800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18801. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18802. this._scene.textures.push(this);
  18803. this._uid = null;
  18804. }
  18805. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18806. get: function () {
  18807. return this._hasAlpha;
  18808. },
  18809. set: function (value) {
  18810. if (this._hasAlpha === value) {
  18811. return;
  18812. }
  18813. this._hasAlpha = value;
  18814. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18820. get: function () {
  18821. return this._coordinatesMode;
  18822. },
  18823. set: function (value) {
  18824. if (this._coordinatesMode === value) {
  18825. return;
  18826. }
  18827. this._coordinatesMode = value;
  18828. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. Object.defineProperty(BaseTexture.prototype, "uid", {
  18834. get: function () {
  18835. if (!this._uid) {
  18836. this._uid = BABYLON.Tools.RandomId();
  18837. }
  18838. return this._uid;
  18839. },
  18840. enumerable: true,
  18841. configurable: true
  18842. });
  18843. BaseTexture.prototype.toString = function () {
  18844. return this.name;
  18845. };
  18846. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18847. set: function (callback) {
  18848. if (this._onDisposeObserver) {
  18849. this.onDisposeObservable.remove(this._onDisposeObserver);
  18850. }
  18851. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18852. },
  18853. enumerable: true,
  18854. configurable: true
  18855. });
  18856. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18857. get: function () {
  18858. return true;
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. BaseTexture.prototype.getScene = function () {
  18864. return this._scene;
  18865. };
  18866. BaseTexture.prototype.getTextureMatrix = function () {
  18867. return null;
  18868. };
  18869. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18870. return null;
  18871. };
  18872. BaseTexture.prototype.getInternalTexture = function () {
  18873. return this._texture;
  18874. };
  18875. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18876. return !this.isBlocking || this.isReady();
  18877. };
  18878. BaseTexture.prototype.isReady = function () {
  18879. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18880. this.delayLoad();
  18881. return false;
  18882. }
  18883. if (this._texture) {
  18884. return this._texture.isReady;
  18885. }
  18886. return false;
  18887. };
  18888. BaseTexture.prototype.getSize = function () {
  18889. if (this._texture._width) {
  18890. return new BABYLON.Size(this._texture._width, this._texture._height);
  18891. }
  18892. if (this._texture._size) {
  18893. return new BABYLON.Size(this._texture._size, this._texture._size);
  18894. }
  18895. return BABYLON.Size.Zero();
  18896. };
  18897. BaseTexture.prototype.getBaseSize = function () {
  18898. if (!this.isReady() || !this._texture)
  18899. return BABYLON.Size.Zero();
  18900. if (this._texture._size) {
  18901. return new BABYLON.Size(this._texture._size, this._texture._size);
  18902. }
  18903. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18904. };
  18905. BaseTexture.prototype.scale = function (ratio) {
  18906. };
  18907. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18908. get: function () {
  18909. return false;
  18910. },
  18911. enumerable: true,
  18912. configurable: true
  18913. });
  18914. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18915. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18916. for (var index = 0; index < texturesCache.length; index++) {
  18917. var texturesCacheEntry = texturesCache[index];
  18918. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18919. texturesCache.splice(index, 1);
  18920. return;
  18921. }
  18922. }
  18923. };
  18924. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18925. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18926. for (var index = 0; index < texturesCache.length; index++) {
  18927. var texturesCacheEntry = texturesCache[index];
  18928. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18929. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18930. texturesCacheEntry.references++;
  18931. return texturesCacheEntry;
  18932. }
  18933. }
  18934. }
  18935. return null;
  18936. };
  18937. BaseTexture.prototype.delayLoad = function () {
  18938. };
  18939. BaseTexture.prototype.clone = function () {
  18940. return null;
  18941. };
  18942. BaseTexture.prototype.releaseInternalTexture = function () {
  18943. if (this._texture) {
  18944. this._scene.getEngine().releaseInternalTexture(this._texture);
  18945. delete this._texture;
  18946. }
  18947. };
  18948. BaseTexture.prototype.dispose = function () {
  18949. // Animations
  18950. this.getScene().stopAnimation(this);
  18951. // Remove from scene
  18952. this._scene._removePendingData(this);
  18953. var index = this._scene.textures.indexOf(this);
  18954. if (index >= 0) {
  18955. this._scene.textures.splice(index, 1);
  18956. }
  18957. if (this._texture === undefined) {
  18958. return;
  18959. }
  18960. // Release
  18961. this.releaseInternalTexture();
  18962. // Callback
  18963. this.onDisposeObservable.notifyObservers(this);
  18964. this.onDisposeObservable.clear();
  18965. };
  18966. BaseTexture.prototype.serialize = function () {
  18967. if (!this.name) {
  18968. return null;
  18969. }
  18970. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18971. // Animations
  18972. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18973. return serializationObject;
  18974. };
  18975. return BaseTexture;
  18976. }());
  18977. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18978. __decorate([
  18979. BABYLON.serialize()
  18980. ], BaseTexture.prototype, "name", void 0);
  18981. __decorate([
  18982. BABYLON.serialize("hasAlpha")
  18983. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18984. __decorate([
  18985. BABYLON.serialize()
  18986. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18987. __decorate([
  18988. BABYLON.serialize()
  18989. ], BaseTexture.prototype, "level", void 0);
  18990. __decorate([
  18991. BABYLON.serialize()
  18992. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18993. __decorate([
  18994. BABYLON.serialize("coordinatesMode")
  18995. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18996. __decorate([
  18997. BABYLON.serialize()
  18998. ], BaseTexture.prototype, "wrapU", void 0);
  18999. __decorate([
  19000. BABYLON.serialize()
  19001. ], BaseTexture.prototype, "wrapV", void 0);
  19002. __decorate([
  19003. BABYLON.serialize()
  19004. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19005. __decorate([
  19006. BABYLON.serialize()
  19007. ], BaseTexture.prototype, "isCube", void 0);
  19008. __decorate([
  19009. BABYLON.serialize()
  19010. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19011. BABYLON.BaseTexture = BaseTexture;
  19012. })(BABYLON || (BABYLON = {}));
  19013. //# sourceMappingURL=babylon.baseTexture.js.map
  19014. var BABYLON;
  19015. (function (BABYLON) {
  19016. var Texture = (function (_super) {
  19017. __extends(Texture, _super);
  19018. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19019. if (noMipmap === void 0) { noMipmap = false; }
  19020. if (invertY === void 0) { invertY = true; }
  19021. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19022. if (onLoad === void 0) { onLoad = null; }
  19023. if (onError === void 0) { onError = null; }
  19024. if (buffer === void 0) { buffer = null; }
  19025. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19026. var _this = _super.call(this, scene) || this;
  19027. _this.uOffset = 0;
  19028. _this.vOffset = 0;
  19029. _this.uScale = 1.0;
  19030. _this.vScale = 1.0;
  19031. _this.uAng = 0;
  19032. _this.vAng = 0;
  19033. _this.wAng = 0;
  19034. _this._isBlocking = true;
  19035. _this.name = url;
  19036. _this.url = url;
  19037. _this._noMipmap = noMipmap;
  19038. _this._invertY = invertY;
  19039. _this._samplingMode = samplingMode;
  19040. _this._buffer = buffer;
  19041. _this._deleteBuffer = deleteBuffer;
  19042. _this._format = format;
  19043. scene = _this.getScene();
  19044. var load = function () {
  19045. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19046. _this.onLoadObservable.notifyObservers(true);
  19047. }
  19048. if (onLoad) {
  19049. onLoad();
  19050. }
  19051. if (!_this.isBlocking) {
  19052. scene.resetCachedMaterial();
  19053. }
  19054. };
  19055. if (!url) {
  19056. _this._delayedOnLoad = load;
  19057. _this._delayedOnError = onError;
  19058. return _this;
  19059. }
  19060. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19061. if (!_this._texture) {
  19062. if (!scene.useDelayedTextureLoading) {
  19063. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19064. if (deleteBuffer) {
  19065. delete _this._buffer;
  19066. }
  19067. }
  19068. else {
  19069. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19070. _this._delayedOnLoad = load;
  19071. _this._delayedOnError = onError;
  19072. }
  19073. }
  19074. else {
  19075. if (_this._texture.isReady) {
  19076. BABYLON.Tools.SetImmediate(function () { return load(); });
  19077. }
  19078. else {
  19079. _this._texture.onLoadedCallbacks.push(load);
  19080. }
  19081. }
  19082. return _this;
  19083. }
  19084. Object.defineProperty(Texture.prototype, "noMipmap", {
  19085. get: function () {
  19086. return this._noMipmap;
  19087. },
  19088. enumerable: true,
  19089. configurable: true
  19090. });
  19091. Object.defineProperty(Texture.prototype, "isBlocking", {
  19092. get: function () {
  19093. return this._isBlocking;
  19094. },
  19095. set: function (value) {
  19096. this._isBlocking = value;
  19097. },
  19098. enumerable: true,
  19099. configurable: true
  19100. });
  19101. Texture.prototype.updateURL = function (url) {
  19102. this.url = url;
  19103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19104. this.delayLoad();
  19105. };
  19106. Texture.prototype.delayLoad = function () {
  19107. var _this = this;
  19108. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19109. return;
  19110. }
  19111. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19112. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19113. if (!this._texture) {
  19114. 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);
  19115. if (this._deleteBuffer) {
  19116. delete this._buffer;
  19117. }
  19118. }
  19119. else {
  19120. if (this._texture.isReady) {
  19121. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19122. }
  19123. else {
  19124. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19125. }
  19126. }
  19127. };
  19128. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19129. if (!this._texture) {
  19130. return;
  19131. }
  19132. this._samplingMode = samplingMode;
  19133. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19134. };
  19135. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19136. x *= this.uScale;
  19137. y *= this.vScale;
  19138. x -= 0.5 * this.uScale;
  19139. y -= 0.5 * this.vScale;
  19140. z -= 0.5;
  19141. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19142. t.x += 0.5 * this.uScale + this.uOffset;
  19143. t.y += 0.5 * this.vScale + this.vOffset;
  19144. t.z += 0.5;
  19145. };
  19146. Texture.prototype.getTextureMatrix = function () {
  19147. if (this.uOffset === this._cachedUOffset &&
  19148. this.vOffset === this._cachedVOffset &&
  19149. this.uScale === this._cachedUScale &&
  19150. this.vScale === this._cachedVScale &&
  19151. this.uAng === this._cachedUAng &&
  19152. this.vAng === this._cachedVAng &&
  19153. this.wAng === this._cachedWAng) {
  19154. return this._cachedTextureMatrix;
  19155. }
  19156. this._cachedUOffset = this.uOffset;
  19157. this._cachedVOffset = this.vOffset;
  19158. this._cachedUScale = this.uScale;
  19159. this._cachedVScale = this.vScale;
  19160. this._cachedUAng = this.uAng;
  19161. this._cachedVAng = this.vAng;
  19162. this._cachedWAng = this.wAng;
  19163. if (!this._cachedTextureMatrix) {
  19164. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19165. this._rowGenerationMatrix = new BABYLON.Matrix();
  19166. this._t0 = BABYLON.Vector3.Zero();
  19167. this._t1 = BABYLON.Vector3.Zero();
  19168. this._t2 = BABYLON.Vector3.Zero();
  19169. }
  19170. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19171. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19172. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19173. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19174. this._t1.subtractInPlace(this._t0);
  19175. this._t2.subtractInPlace(this._t0);
  19176. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19177. this._cachedTextureMatrix.m[0] = this._t1.x;
  19178. this._cachedTextureMatrix.m[1] = this._t1.y;
  19179. this._cachedTextureMatrix.m[2] = this._t1.z;
  19180. this._cachedTextureMatrix.m[4] = this._t2.x;
  19181. this._cachedTextureMatrix.m[5] = this._t2.y;
  19182. this._cachedTextureMatrix.m[6] = this._t2.z;
  19183. this._cachedTextureMatrix.m[8] = this._t0.x;
  19184. this._cachedTextureMatrix.m[9] = this._t0.y;
  19185. this._cachedTextureMatrix.m[10] = this._t0.z;
  19186. return this._cachedTextureMatrix;
  19187. };
  19188. Texture.prototype.getReflectionTextureMatrix = function () {
  19189. if (this.uOffset === this._cachedUOffset &&
  19190. this.vOffset === this._cachedVOffset &&
  19191. this.uScale === this._cachedUScale &&
  19192. this.vScale === this._cachedVScale &&
  19193. this.coordinatesMode === this._cachedCoordinatesMode) {
  19194. return this._cachedTextureMatrix;
  19195. }
  19196. if (!this._cachedTextureMatrix) {
  19197. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19198. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19199. }
  19200. this._cachedCoordinatesMode = this.coordinatesMode;
  19201. switch (this.coordinatesMode) {
  19202. case Texture.PLANAR_MODE:
  19203. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19204. this._cachedTextureMatrix[0] = this.uScale;
  19205. this._cachedTextureMatrix[5] = this.vScale;
  19206. this._cachedTextureMatrix[12] = this.uOffset;
  19207. this._cachedTextureMatrix[13] = this.vOffset;
  19208. break;
  19209. case Texture.PROJECTION_MODE:
  19210. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19211. this._projectionModeMatrix.m[0] = 0.5;
  19212. this._projectionModeMatrix.m[5] = -0.5;
  19213. this._projectionModeMatrix.m[10] = 0.0;
  19214. this._projectionModeMatrix.m[12] = 0.5;
  19215. this._projectionModeMatrix.m[13] = 0.5;
  19216. this._projectionModeMatrix.m[14] = 1.0;
  19217. this._projectionModeMatrix.m[15] = 1.0;
  19218. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19219. break;
  19220. default:
  19221. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19222. break;
  19223. }
  19224. return this._cachedTextureMatrix;
  19225. };
  19226. Texture.prototype.clone = function () {
  19227. var _this = this;
  19228. return BABYLON.SerializationHelper.Clone(function () {
  19229. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19230. }, this);
  19231. };
  19232. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19233. get: function () {
  19234. if (!this._onLoadObservarble) {
  19235. this._onLoadObservarble = new BABYLON.Observable();
  19236. }
  19237. return this._onLoadObservarble;
  19238. },
  19239. enumerable: true,
  19240. configurable: true
  19241. });
  19242. // Statics
  19243. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19244. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19245. if (onLoad === void 0) { onLoad = null; }
  19246. if (onError === void 0) { onError = null; }
  19247. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19248. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19249. };
  19250. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19251. if (parsedTexture.customType) {
  19252. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19253. // Update Sampling Mode
  19254. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19255. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19256. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19257. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19258. }
  19259. }
  19260. return parsedCustomTexture;
  19261. }
  19262. if (parsedTexture.isCube) {
  19263. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19264. }
  19265. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19266. return null;
  19267. }
  19268. var texture = BABYLON.SerializationHelper.Parse(function () {
  19269. if (parsedTexture.mirrorPlane) {
  19270. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19271. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19272. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19273. return mirrorTexture;
  19274. }
  19275. else if (parsedTexture.isRenderTarget) {
  19276. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19277. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19278. return renderTargetTexture;
  19279. }
  19280. else {
  19281. var texture;
  19282. if (parsedTexture.base64String) {
  19283. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19284. }
  19285. else {
  19286. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19287. }
  19288. return texture;
  19289. }
  19290. }, parsedTexture, scene);
  19291. // Update Sampling Mode
  19292. if (parsedTexture.samplingMode) {
  19293. var sampling = parsedTexture.samplingMode;
  19294. if (texture._samplingMode !== sampling) {
  19295. texture.updateSamplingMode(sampling);
  19296. }
  19297. }
  19298. // Animations
  19299. if (parsedTexture.animations) {
  19300. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19301. var parsedAnimation = parsedTexture.animations[animationIndex];
  19302. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19303. }
  19304. }
  19305. return texture;
  19306. };
  19307. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19308. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19309. if (noMipmap === void 0) { noMipmap = false; }
  19310. if (invertY === void 0) { invertY = true; }
  19311. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19312. if (onLoad === void 0) { onLoad = null; }
  19313. if (onError === void 0) { onError = null; }
  19314. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19315. if (name.substr(0, 5) !== "data:") {
  19316. name = "data:" + name;
  19317. }
  19318. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19319. };
  19320. return Texture;
  19321. }(BABYLON.BaseTexture));
  19322. // Constants
  19323. Texture.NEAREST_SAMPLINGMODE = 1;
  19324. Texture.BILINEAR_SAMPLINGMODE = 2;
  19325. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19326. Texture.EXPLICIT_MODE = 0;
  19327. Texture.SPHERICAL_MODE = 1;
  19328. Texture.PLANAR_MODE = 2;
  19329. Texture.CUBIC_MODE = 3;
  19330. Texture.PROJECTION_MODE = 4;
  19331. Texture.SKYBOX_MODE = 5;
  19332. Texture.INVCUBIC_MODE = 6;
  19333. Texture.EQUIRECTANGULAR_MODE = 7;
  19334. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19335. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19336. Texture.CLAMP_ADDRESSMODE = 0;
  19337. Texture.WRAP_ADDRESSMODE = 1;
  19338. Texture.MIRROR_ADDRESSMODE = 2;
  19339. __decorate([
  19340. BABYLON.serialize()
  19341. ], Texture.prototype, "url", void 0);
  19342. __decorate([
  19343. BABYLON.serialize()
  19344. ], Texture.prototype, "uOffset", void 0);
  19345. __decorate([
  19346. BABYLON.serialize()
  19347. ], Texture.prototype, "vOffset", void 0);
  19348. __decorate([
  19349. BABYLON.serialize()
  19350. ], Texture.prototype, "uScale", void 0);
  19351. __decorate([
  19352. BABYLON.serialize()
  19353. ], Texture.prototype, "vScale", void 0);
  19354. __decorate([
  19355. BABYLON.serialize()
  19356. ], Texture.prototype, "uAng", void 0);
  19357. __decorate([
  19358. BABYLON.serialize()
  19359. ], Texture.prototype, "vAng", void 0);
  19360. __decorate([
  19361. BABYLON.serialize()
  19362. ], Texture.prototype, "wAng", void 0);
  19363. __decorate([
  19364. BABYLON.serialize()
  19365. ], Texture.prototype, "isBlocking", null);
  19366. BABYLON.Texture = Texture;
  19367. })(BABYLON || (BABYLON = {}));
  19368. //# sourceMappingURL=babylon.texture.js.map
  19369. var BABYLON;
  19370. (function (BABYLON) {
  19371. var _InstancesBatch = (function () {
  19372. function _InstancesBatch() {
  19373. this.mustReturn = false;
  19374. this.visibleInstances = new Array();
  19375. this.renderSelf = new Array();
  19376. }
  19377. return _InstancesBatch;
  19378. }());
  19379. BABYLON._InstancesBatch = _InstancesBatch;
  19380. var Mesh = (function (_super) {
  19381. __extends(Mesh, _super);
  19382. /**
  19383. * @constructor
  19384. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19385. * @param {Scene} scene The scene to add this mesh to.
  19386. * @param {Node} parent The parent of this mesh, if it has one
  19387. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19388. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19389. * When false, achieved by calling a clone(), also passing False.
  19390. * This will make creation of children, recursive.
  19391. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19392. */
  19393. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19394. if (parent === void 0) { parent = null; }
  19395. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19396. var _this = _super.call(this, name, scene) || this;
  19397. // Events
  19398. /**
  19399. * An event triggered before rendering the mesh
  19400. * @type {BABYLON.Observable}
  19401. */
  19402. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19403. /**
  19404. * An event triggered after rendering the mesh
  19405. * @type {BABYLON.Observable}
  19406. */
  19407. _this.onAfterRenderObservable = new BABYLON.Observable();
  19408. /**
  19409. * An event triggered before drawing the mesh
  19410. * @type {BABYLON.Observable}
  19411. */
  19412. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19413. // Members
  19414. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19415. _this.instances = new Array();
  19416. _this._LODLevels = new Array();
  19417. _this._visibleInstances = {};
  19418. _this._renderIdForInstances = new Array();
  19419. _this._batchCache = new _InstancesBatch();
  19420. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19421. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19422. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19423. // Will be used to save a source mesh reference, If any
  19424. _this._source = null;
  19425. if (source) {
  19426. // Source mesh
  19427. _this._source = source;
  19428. // Geometry
  19429. if (source._geometry) {
  19430. source._geometry.applyToMesh(_this);
  19431. }
  19432. // Deep copy
  19433. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19434. // Parent
  19435. _this.parent = source.parent;
  19436. // Pivot
  19437. _this.setPivotMatrix(source.getPivotMatrix());
  19438. _this.id = name + "." + source.id;
  19439. // Material
  19440. _this.material = source.material;
  19441. var index;
  19442. if (!doNotCloneChildren) {
  19443. // Children
  19444. for (index = 0; index < scene.meshes.length; index++) {
  19445. var mesh = scene.meshes[index];
  19446. if (mesh.parent === source) {
  19447. // doNotCloneChildren is always going to be False
  19448. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19449. }
  19450. }
  19451. }
  19452. // Physics clone
  19453. var physicsEngine = _this.getScene().getPhysicsEngine();
  19454. if (clonePhysicsImpostor && physicsEngine) {
  19455. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19456. if (impostor) {
  19457. _this.physicsImpostor = impostor.clone(_this);
  19458. }
  19459. }
  19460. // Particles
  19461. for (index = 0; index < scene.particleSystems.length; index++) {
  19462. var system = scene.particleSystems[index];
  19463. if (system.emitter === source) {
  19464. system.clone(system.name, _this);
  19465. }
  19466. }
  19467. _this.computeWorldMatrix(true);
  19468. }
  19469. // Parent
  19470. if (parent !== null) {
  19471. _this.parent = parent;
  19472. }
  19473. return _this;
  19474. }
  19475. Object.defineProperty(Mesh, "FRONTSIDE", {
  19476. /**
  19477. * Mesh side orientation : usually the external or front surface
  19478. */
  19479. get: function () {
  19480. return Mesh._FRONTSIDE;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(Mesh, "BACKSIDE", {
  19486. /**
  19487. * Mesh side orientation : usually the internal or back surface
  19488. */
  19489. get: function () {
  19490. return Mesh._BACKSIDE;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19496. /**
  19497. * Mesh side orientation : both internal and external or front and back surfaces
  19498. */
  19499. get: function () {
  19500. return Mesh._DOUBLESIDE;
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19506. /**
  19507. * Mesh side orientation : by default, `FRONTSIDE`
  19508. */
  19509. get: function () {
  19510. return Mesh._DEFAULTSIDE;
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(Mesh, "NO_CAP", {
  19516. /**
  19517. * Mesh cap setting : no cap
  19518. */
  19519. get: function () {
  19520. return Mesh._NO_CAP;
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(Mesh, "CAP_START", {
  19526. /**
  19527. * Mesh cap setting : one cap at the beginning of the mesh
  19528. */
  19529. get: function () {
  19530. return Mesh._CAP_START;
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Object.defineProperty(Mesh, "CAP_END", {
  19536. /**
  19537. * Mesh cap setting : one cap at the end of the mesh
  19538. */
  19539. get: function () {
  19540. return Mesh._CAP_END;
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(Mesh, "CAP_ALL", {
  19546. /**
  19547. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19548. */
  19549. get: function () {
  19550. return Mesh._CAP_ALL;
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19556. set: function (callback) {
  19557. if (this._onBeforeDrawObserver) {
  19558. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19559. }
  19560. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19566. get: function () {
  19567. return this._morphTargetManager;
  19568. },
  19569. set: function (value) {
  19570. if (this._morphTargetManager === value) {
  19571. return;
  19572. }
  19573. this._morphTargetManager = value;
  19574. this._syncGeometryWithMorphTargetManager();
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Mesh.prototype, "source", {
  19580. get: function () {
  19581. return this._source;
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. // Methods
  19587. /**
  19588. * Returns the string "Mesh".
  19589. */
  19590. Mesh.prototype.getClassName = function () {
  19591. return "Mesh";
  19592. };
  19593. /**
  19594. * Returns a string.
  19595. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19596. */
  19597. Mesh.prototype.toString = function (fullDetails) {
  19598. var ret = _super.prototype.toString.call(this, fullDetails);
  19599. ret += ", n vertices: " + this.getTotalVertices();
  19600. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19601. if (this.animations) {
  19602. for (var i = 0; i < this.animations.length; i++) {
  19603. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19604. }
  19605. }
  19606. if (fullDetails) {
  19607. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19608. }
  19609. return ret;
  19610. };
  19611. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19612. /**
  19613. * True if the mesh has some Levels Of Details (LOD).
  19614. * Returns a boolean.
  19615. */
  19616. get: function () {
  19617. return this._LODLevels.length > 0;
  19618. },
  19619. enumerable: true,
  19620. configurable: true
  19621. });
  19622. Mesh.prototype._sortLODLevels = function () {
  19623. this._LODLevels.sort(function (a, b) {
  19624. if (a.distance < b.distance) {
  19625. return 1;
  19626. }
  19627. if (a.distance > b.distance) {
  19628. return -1;
  19629. }
  19630. return 0;
  19631. });
  19632. };
  19633. /**
  19634. * Add a mesh as LOD level triggered at the given distance.
  19635. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19636. * @param {number} distance The distance from the center of the object to show this level
  19637. * @param {Mesh} mesh The mesh to be added as LOD level
  19638. * @return {Mesh} This mesh (for chaining)
  19639. */
  19640. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19641. if (mesh && mesh._masterMesh) {
  19642. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19643. return this;
  19644. }
  19645. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19646. this._LODLevels.push(level);
  19647. if (mesh) {
  19648. mesh._masterMesh = this;
  19649. }
  19650. this._sortLODLevels();
  19651. return this;
  19652. };
  19653. /**
  19654. * Returns the LOD level mesh at the passed distance or null if not found.
  19655. * It is related to the method `addLODLevel(distance, mesh)`.
  19656. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19657. * Returns an object Mesh or `null`.
  19658. */
  19659. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19660. for (var index = 0; index < this._LODLevels.length; index++) {
  19661. var level = this._LODLevels[index];
  19662. if (level.distance === distance) {
  19663. return level.mesh;
  19664. }
  19665. }
  19666. return null;
  19667. };
  19668. /**
  19669. * Remove a mesh from the LOD array
  19670. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19671. * @param {Mesh} mesh The mesh to be removed.
  19672. * @return {Mesh} This mesh (for chaining)
  19673. */
  19674. Mesh.prototype.removeLODLevel = function (mesh) {
  19675. for (var index = 0; index < this._LODLevels.length; index++) {
  19676. if (this._LODLevels[index].mesh === mesh) {
  19677. this._LODLevels.splice(index, 1);
  19678. if (mesh) {
  19679. mesh._masterMesh = null;
  19680. }
  19681. }
  19682. }
  19683. this._sortLODLevels();
  19684. return this;
  19685. };
  19686. /**
  19687. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19688. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19689. */
  19690. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19691. if (!this._LODLevels || this._LODLevels.length === 0) {
  19692. return this;
  19693. }
  19694. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19695. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19696. if (this.onLODLevelSelection) {
  19697. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19698. }
  19699. return this;
  19700. }
  19701. for (var index = 0; index < this._LODLevels.length; index++) {
  19702. var level = this._LODLevels[index];
  19703. if (level.distance < distanceToCamera) {
  19704. if (level.mesh) {
  19705. level.mesh._preActivate();
  19706. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19707. }
  19708. if (this.onLODLevelSelection) {
  19709. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19710. }
  19711. return level.mesh;
  19712. }
  19713. }
  19714. if (this.onLODLevelSelection) {
  19715. this.onLODLevelSelection(distanceToCamera, this, this);
  19716. }
  19717. return this;
  19718. };
  19719. Object.defineProperty(Mesh.prototype, "geometry", {
  19720. /**
  19721. * Returns the mesh internal Geometry object.
  19722. */
  19723. get: function () {
  19724. return this._geometry;
  19725. },
  19726. enumerable: true,
  19727. configurable: true
  19728. });
  19729. /**
  19730. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19731. */
  19732. Mesh.prototype.getTotalVertices = function () {
  19733. if (!this._geometry) {
  19734. return 0;
  19735. }
  19736. return this._geometry.getTotalVertices();
  19737. };
  19738. /**
  19739. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19740. * 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.
  19741. * You can force the copy with forceCopy === true
  19742. * Returns null if the mesh has no geometry or no vertex buffer.
  19743. * Possible `kind` values :
  19744. * - BABYLON.VertexBuffer.PositionKind
  19745. * - BABYLON.VertexBuffer.UVKind
  19746. * - BABYLON.VertexBuffer.UV2Kind
  19747. * - BABYLON.VertexBuffer.UV3Kind
  19748. * - BABYLON.VertexBuffer.UV4Kind
  19749. * - BABYLON.VertexBuffer.UV5Kind
  19750. * - BABYLON.VertexBuffer.UV6Kind
  19751. * - BABYLON.VertexBuffer.ColorKind
  19752. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19753. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19754. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19755. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19756. */
  19757. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19758. if (!this._geometry) {
  19759. return null;
  19760. }
  19761. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19762. };
  19763. /**
  19764. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19765. * Returns `undefined` if the mesh has no geometry.
  19766. * Possible `kind` values :
  19767. * - BABYLON.VertexBuffer.PositionKind
  19768. * - BABYLON.VertexBuffer.UVKind
  19769. * - BABYLON.VertexBuffer.UV2Kind
  19770. * - BABYLON.VertexBuffer.UV3Kind
  19771. * - BABYLON.VertexBuffer.UV4Kind
  19772. * - BABYLON.VertexBuffer.UV5Kind
  19773. * - BABYLON.VertexBuffer.UV6Kind
  19774. * - BABYLON.VertexBuffer.ColorKind
  19775. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19776. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19777. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19778. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19779. */
  19780. Mesh.prototype.getVertexBuffer = function (kind) {
  19781. if (!this._geometry) {
  19782. return undefined;
  19783. }
  19784. return this._geometry.getVertexBuffer(kind);
  19785. };
  19786. /**
  19787. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19788. * Possible `kind` values :
  19789. * - BABYLON.VertexBuffer.PositionKind
  19790. * - BABYLON.VertexBuffer.UVKind
  19791. * - BABYLON.VertexBuffer.UV2Kind
  19792. * - BABYLON.VertexBuffer.UV3Kind
  19793. * - BABYLON.VertexBuffer.UV4Kind
  19794. * - BABYLON.VertexBuffer.UV5Kind
  19795. * - BABYLON.VertexBuffer.UV6Kind
  19796. * - BABYLON.VertexBuffer.ColorKind
  19797. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19798. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19799. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19800. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19801. */
  19802. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19803. if (!this._geometry) {
  19804. if (this._delayInfo) {
  19805. return this._delayInfo.indexOf(kind) !== -1;
  19806. }
  19807. return false;
  19808. }
  19809. return this._geometry.isVerticesDataPresent(kind);
  19810. };
  19811. /**
  19812. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19813. * Possible `kind` values :
  19814. * - BABYLON.VertexBuffer.PositionKind
  19815. * - BABYLON.VertexBuffer.UVKind
  19816. * - BABYLON.VertexBuffer.UV2Kind
  19817. * - BABYLON.VertexBuffer.UV3Kind
  19818. * - BABYLON.VertexBuffer.UV4Kind
  19819. * - BABYLON.VertexBuffer.UV5Kind
  19820. * - BABYLON.VertexBuffer.UV6Kind
  19821. * - BABYLON.VertexBuffer.ColorKind
  19822. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19823. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19824. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19825. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19826. */
  19827. Mesh.prototype.getVerticesDataKinds = function () {
  19828. if (!this._geometry) {
  19829. var result = [];
  19830. if (this._delayInfo) {
  19831. this._delayInfo.forEach(function (kind, index, array) {
  19832. result.push(kind);
  19833. });
  19834. }
  19835. return result;
  19836. }
  19837. return this._geometry.getVerticesDataKinds();
  19838. };
  19839. /**
  19840. * Returns a positive integer : the total number of indices in this mesh geometry.
  19841. * Returns zero if the mesh has no geometry.
  19842. */
  19843. Mesh.prototype.getTotalIndices = function () {
  19844. if (!this._geometry) {
  19845. return 0;
  19846. }
  19847. return this._geometry.getTotalIndices();
  19848. };
  19849. /**
  19850. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19851. * 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.
  19852. * Returns an empty array if the mesh has no geometry.
  19853. */
  19854. Mesh.prototype.getIndices = function (copyWhenShared) {
  19855. if (!this._geometry) {
  19856. return [];
  19857. }
  19858. return this._geometry.getIndices(copyWhenShared);
  19859. };
  19860. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19861. get: function () {
  19862. return this._masterMesh !== null && this._masterMesh !== undefined;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. /**
  19868. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19869. */
  19870. Mesh.prototype.isReady = function () {
  19871. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19872. return false;
  19873. }
  19874. return _super.prototype.isReady.call(this);
  19875. };
  19876. /**
  19877. * Boolean : true if the mesh has been disposed.
  19878. */
  19879. Mesh.prototype.isDisposed = function () {
  19880. return this._isDisposed;
  19881. };
  19882. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19883. get: function () {
  19884. return this._sideOrientation;
  19885. },
  19886. /**
  19887. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19888. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19889. */
  19890. set: function (sideO) {
  19891. this._sideOrientation = sideO;
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19897. /**
  19898. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19899. * This property is pertinent only for updatable parametric shapes.
  19900. */
  19901. get: function () {
  19902. return this._areNormalsFrozen;
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. /**
  19908. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19909. * It has no effect at all on other shapes.
  19910. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19911. * Returns the Mesh.
  19912. */
  19913. Mesh.prototype.freezeNormals = function () {
  19914. this._areNormalsFrozen = true;
  19915. return this;
  19916. };
  19917. /**
  19918. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19919. * It has no effect at all on other shapes.
  19920. * It reactivates the mesh normals computation if it was previously frozen.
  19921. * Returns the Mesh.
  19922. */
  19923. Mesh.prototype.unfreezeNormals = function () {
  19924. this._areNormalsFrozen = false;
  19925. return this;
  19926. };
  19927. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19928. /**
  19929. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19930. */
  19931. set: function (count) {
  19932. this._overridenInstanceCount = count;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. // Methods
  19938. Mesh.prototype._preActivate = function () {
  19939. var sceneRenderId = this.getScene().getRenderId();
  19940. if (this._preActivateId === sceneRenderId) {
  19941. return this;
  19942. }
  19943. this._preActivateId = sceneRenderId;
  19944. this._visibleInstances = null;
  19945. return this;
  19946. };
  19947. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19948. if (this._visibleInstances) {
  19949. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19950. }
  19951. return this;
  19952. };
  19953. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19954. if (!this._visibleInstances) {
  19955. this._visibleInstances = {};
  19956. this._visibleInstances.defaultRenderId = renderId;
  19957. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19958. }
  19959. if (!this._visibleInstances[renderId]) {
  19960. this._visibleInstances[renderId] = new Array();
  19961. }
  19962. this._visibleInstances[renderId].push(instance);
  19963. return this;
  19964. };
  19965. /**
  19966. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19967. * This means the mesh underlying bounding box and sphere are recomputed.
  19968. * Returns the Mesh.
  19969. */
  19970. Mesh.prototype.refreshBoundingInfo = function () {
  19971. if (this._boundingInfo.isLocked) {
  19972. return;
  19973. }
  19974. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19975. if (data) {
  19976. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19977. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19978. }
  19979. if (this.subMeshes) {
  19980. for (var index = 0; index < this.subMeshes.length; index++) {
  19981. this.subMeshes[index].refreshBoundingInfo();
  19982. }
  19983. }
  19984. this._updateBoundingInfo();
  19985. return this;
  19986. };
  19987. Mesh.prototype._createGlobalSubMesh = function () {
  19988. var totalVertices = this.getTotalVertices();
  19989. if (!totalVertices || !this.getIndices()) {
  19990. return null;
  19991. }
  19992. this.releaseSubMeshes();
  19993. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19994. };
  19995. Mesh.prototype.subdivide = function (count) {
  19996. if (count < 1) {
  19997. return;
  19998. }
  19999. var totalIndices = this.getTotalIndices();
  20000. var subdivisionSize = (totalIndices / count) | 0;
  20001. var offset = 0;
  20002. // Ensure that subdivisionSize is a multiple of 3
  20003. while (subdivisionSize % 3 !== 0) {
  20004. subdivisionSize++;
  20005. }
  20006. this.releaseSubMeshes();
  20007. for (var index = 0; index < count; index++) {
  20008. if (offset >= totalIndices) {
  20009. break;
  20010. }
  20011. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20012. offset += subdivisionSize;
  20013. }
  20014. this.synchronizeInstances();
  20015. };
  20016. /**
  20017. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20018. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20019. * The `data` are either a numeric array either a Float32Array.
  20020. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20021. * 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).
  20022. * Note that a new underlying VertexBuffer object is created each call.
  20023. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20024. *
  20025. * Possible `kind` values :
  20026. * - BABYLON.VertexBuffer.PositionKind
  20027. * - BABYLON.VertexBuffer.UVKind
  20028. * - BABYLON.VertexBuffer.UV2Kind
  20029. * - BABYLON.VertexBuffer.UV3Kind
  20030. * - BABYLON.VertexBuffer.UV4Kind
  20031. * - BABYLON.VertexBuffer.UV5Kind
  20032. * - BABYLON.VertexBuffer.UV6Kind
  20033. * - BABYLON.VertexBuffer.ColorKind
  20034. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20035. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20036. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20037. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20038. *
  20039. * Returns the Mesh.
  20040. */
  20041. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20042. if (!this._geometry) {
  20043. var vertexData = new BABYLON.VertexData();
  20044. vertexData.set(data, kind);
  20045. var scene = this.getScene();
  20046. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20047. }
  20048. else {
  20049. this._geometry.setVerticesData(kind, data, updatable, stride);
  20050. }
  20051. return this;
  20052. };
  20053. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20054. if (updatable === void 0) { updatable = true; }
  20055. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20056. return;
  20057. }
  20058. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20059. };
  20060. /**
  20061. * Sets the mesh VertexBuffer.
  20062. * Returns the Mesh.
  20063. */
  20064. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20065. if (!this._geometry) {
  20066. var scene = this.getScene();
  20067. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20068. }
  20069. this._geometry.setVerticesBuffer(buffer);
  20070. return this;
  20071. };
  20072. /**
  20073. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20074. * If the mesh has no geometry, it is simply returned as it is.
  20075. * The `data` are either a numeric array either a Float32Array.
  20076. * No new underlying VertexBuffer object is created.
  20077. * 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.
  20078. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20079. *
  20080. * Possible `kind` values :
  20081. * - BABYLON.VertexBuffer.PositionKind
  20082. * - BABYLON.VertexBuffer.UVKind
  20083. * - BABYLON.VertexBuffer.UV2Kind
  20084. * - BABYLON.VertexBuffer.UV3Kind
  20085. * - BABYLON.VertexBuffer.UV4Kind
  20086. * - BABYLON.VertexBuffer.UV5Kind
  20087. * - BABYLON.VertexBuffer.UV6Kind
  20088. * - BABYLON.VertexBuffer.ColorKind
  20089. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20090. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20091. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20092. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20093. *
  20094. * Returns the Mesh.
  20095. */
  20096. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20097. if (!this._geometry) {
  20098. return;
  20099. }
  20100. if (!makeItUnique) {
  20101. this._geometry.updateVerticesData(kind, data, updateExtends);
  20102. }
  20103. else {
  20104. this.makeGeometryUnique();
  20105. this.updateVerticesData(kind, data, updateExtends, false);
  20106. }
  20107. return this;
  20108. };
  20109. /**
  20110. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20111. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20112. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20113. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20114. * Returns the Mesh.
  20115. */
  20116. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20117. if (computeNormals === void 0) { computeNormals = true; }
  20118. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20119. positionFunction(positions);
  20120. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20121. if (computeNormals) {
  20122. var indices = this.getIndices();
  20123. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20124. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20125. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20126. }
  20127. return this;
  20128. };
  20129. /**
  20130. * This method will force the computation of normals for the mesh.
  20131. * Please note that the mesh must have normals vertex data already.
  20132. * Returns the Mesh.
  20133. */
  20134. Mesh.prototype.recomputeNormals = function (markDataAsUpdatable) {
  20135. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20136. var indices = this.getIndices();
  20137. var normals;
  20138. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20139. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20140. }
  20141. else {
  20142. normals = [];
  20143. }
  20144. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20145. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, markDataAsUpdatable);
  20146. return this;
  20147. };
  20148. /**
  20149. * Creates a un-shared specific occurence of the geometry for the mesh.
  20150. * Returns the Mesh.
  20151. */
  20152. Mesh.prototype.makeGeometryUnique = function () {
  20153. if (!this._geometry) {
  20154. return;
  20155. }
  20156. var oldGeometry = this._geometry;
  20157. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20158. oldGeometry.releaseForMesh(this, true);
  20159. geometry.applyToMesh(this);
  20160. return this;
  20161. };
  20162. /**
  20163. * Sets the mesh indices.
  20164. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20165. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20166. * This method creates a new index buffer each call.
  20167. * Returns the Mesh.
  20168. */
  20169. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20170. if (!this._geometry) {
  20171. var vertexData = new BABYLON.VertexData();
  20172. vertexData.indices = indices;
  20173. var scene = this.getScene();
  20174. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20175. }
  20176. else {
  20177. this._geometry.setIndices(indices, totalVertices);
  20178. }
  20179. return this;
  20180. };
  20181. /**
  20182. * Invert the geometry to move from a right handed system to a left handed one.
  20183. * Returns the Mesh.
  20184. */
  20185. Mesh.prototype.toLeftHanded = function () {
  20186. if (!this._geometry) {
  20187. return;
  20188. }
  20189. this._geometry.toLeftHanded();
  20190. return this;
  20191. };
  20192. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20193. var engine = this.getScene().getEngine();
  20194. // Wireframe
  20195. var indexToBind;
  20196. if (this._unIndexed) {
  20197. indexToBind = null;
  20198. }
  20199. else {
  20200. switch (fillMode) {
  20201. case BABYLON.Material.PointFillMode:
  20202. indexToBind = null;
  20203. break;
  20204. case BABYLON.Material.WireFrameFillMode:
  20205. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20206. break;
  20207. default:
  20208. case BABYLON.Material.TriangleFillMode:
  20209. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20210. break;
  20211. }
  20212. }
  20213. // VBOs
  20214. this._geometry._bind(effect, indexToBind);
  20215. return this;
  20216. };
  20217. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20218. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20219. return this;
  20220. }
  20221. this.onBeforeDrawObservable.notifyObservers(this);
  20222. var engine = this.getScene().getEngine();
  20223. // Draw order
  20224. switch (fillMode) {
  20225. case BABYLON.Material.PointFillMode:
  20226. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20227. break;
  20228. case BABYLON.Material.WireFrameFillMode:
  20229. if (this._unIndexed) {
  20230. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20231. }
  20232. else {
  20233. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20234. }
  20235. break;
  20236. default:
  20237. if (this._unIndexed) {
  20238. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20239. }
  20240. else {
  20241. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20242. }
  20243. }
  20244. return this;
  20245. };
  20246. /**
  20247. * Registers for this mesh a javascript function called just before the rendering process.
  20248. * This function is passed the current mesh.
  20249. * Return the Mesh.
  20250. */
  20251. Mesh.prototype.registerBeforeRender = function (func) {
  20252. this.onBeforeRenderObservable.add(func);
  20253. return this;
  20254. };
  20255. /**
  20256. * Disposes a previously registered javascript function called before the rendering.
  20257. * This function is passed the current mesh.
  20258. * Returns the Mesh.
  20259. */
  20260. Mesh.prototype.unregisterBeforeRender = function (func) {
  20261. this.onBeforeRenderObservable.removeCallback(func);
  20262. return this;
  20263. };
  20264. /**
  20265. * Registers for this mesh a javascript function called just after the rendering is complete.
  20266. * This function is passed the current mesh.
  20267. * Returns the Mesh.
  20268. */
  20269. Mesh.prototype.registerAfterRender = function (func) {
  20270. this.onAfterRenderObservable.add(func);
  20271. return this;
  20272. };
  20273. /**
  20274. * Disposes a previously registered javascript function called after the rendering.
  20275. * This function is passed the current mesh.
  20276. * Return the Mesh.
  20277. */
  20278. Mesh.prototype.unregisterAfterRender = function (func) {
  20279. this.onAfterRenderObservable.removeCallback(func);
  20280. return this;
  20281. };
  20282. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20283. var scene = this.getScene();
  20284. this._batchCache.mustReturn = false;
  20285. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20286. this._batchCache.visibleInstances[subMeshId] = null;
  20287. if (this._visibleInstances) {
  20288. var currentRenderId = scene.getRenderId();
  20289. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20290. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20291. var selfRenderId = this._renderId;
  20292. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20293. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20294. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20295. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20296. }
  20297. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20298. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20299. this._batchCache.mustReturn = true;
  20300. return this._batchCache;
  20301. }
  20302. if (currentRenderId !== selfRenderId) {
  20303. this._batchCache.renderSelf[subMeshId] = false;
  20304. }
  20305. }
  20306. this._renderIdForInstances[subMeshId] = currentRenderId;
  20307. }
  20308. return this._batchCache;
  20309. };
  20310. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20311. var visibleInstances = batch.visibleInstances[subMesh._id];
  20312. var matricesCount = visibleInstances.length + 1;
  20313. var bufferSize = matricesCount * 16 * 4;
  20314. var currentInstancesBufferSize = this._instancesBufferSize;
  20315. var instancesBuffer = this._instancesBuffer;
  20316. while (this._instancesBufferSize < bufferSize) {
  20317. this._instancesBufferSize *= 2;
  20318. }
  20319. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20320. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20321. }
  20322. var offset = 0;
  20323. var instancesCount = 0;
  20324. var world = this.getWorldMatrix();
  20325. if (batch.renderSelf[subMesh._id]) {
  20326. world.copyToArray(this._instancesData, offset);
  20327. offset += 16;
  20328. instancesCount++;
  20329. }
  20330. if (visibleInstances) {
  20331. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20332. var instance = visibleInstances[instanceIndex];
  20333. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20334. offset += 16;
  20335. instancesCount++;
  20336. }
  20337. }
  20338. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20339. if (instancesBuffer) {
  20340. instancesBuffer.dispose();
  20341. }
  20342. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20343. this._instancesBuffer = instancesBuffer;
  20344. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20345. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20346. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20347. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20348. }
  20349. else {
  20350. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20351. }
  20352. this.geometry._bind(effect);
  20353. this._draw(subMesh, fillMode, instancesCount);
  20354. engine.unbindInstanceAttributes();
  20355. return this;
  20356. };
  20357. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20358. var scene = this.getScene();
  20359. var engine = scene.getEngine();
  20360. if (hardwareInstancedRendering) {
  20361. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20362. }
  20363. else {
  20364. if (batch.renderSelf[subMesh._id]) {
  20365. // Draw
  20366. if (onBeforeDraw) {
  20367. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20368. }
  20369. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20370. }
  20371. if (batch.visibleInstances[subMesh._id]) {
  20372. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20373. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20374. // World
  20375. var world = instance.getWorldMatrix();
  20376. if (onBeforeDraw) {
  20377. onBeforeDraw(true, world, effectiveMaterial);
  20378. }
  20379. // Draw
  20380. this._draw(subMesh, fillMode);
  20381. }
  20382. }
  20383. }
  20384. return this;
  20385. };
  20386. /**
  20387. * Triggers the draw call for the mesh.
  20388. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20389. * Returns the Mesh.
  20390. */
  20391. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20392. var scene = this.getScene();
  20393. // Managing instances
  20394. var batch = this._getInstancesRenderList(subMesh._id);
  20395. if (batch.mustReturn) {
  20396. return this;
  20397. }
  20398. // Checking geometry state
  20399. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20400. return this;
  20401. }
  20402. var callbackIndex;
  20403. this.onBeforeRenderObservable.notifyObservers(this);
  20404. var engine = scene.getEngine();
  20405. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20406. // Material
  20407. var effectiveMaterial = subMesh.getMaterial();
  20408. if (!effectiveMaterial) {
  20409. return this;
  20410. }
  20411. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20412. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20413. return this;
  20414. }
  20415. }
  20416. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20417. return this;
  20418. }
  20419. // Alpha mode
  20420. if (enableAlphaMode) {
  20421. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20422. }
  20423. // Outline - step 1
  20424. var savedDepthWrite = engine.getDepthWrite();
  20425. if (this.renderOutline) {
  20426. engine.setDepthWrite(false);
  20427. scene.getOutlineRenderer().render(subMesh, batch);
  20428. engine.setDepthWrite(savedDepthWrite);
  20429. }
  20430. var effect;
  20431. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20432. effect = subMesh.effect;
  20433. }
  20434. else {
  20435. effect = effectiveMaterial.getEffect();
  20436. }
  20437. effectiveMaterial._preBind(effect);
  20438. // Bind
  20439. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20440. this._bind(subMesh, effect, fillMode);
  20441. var world = this.getWorldMatrix();
  20442. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20443. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20444. }
  20445. else {
  20446. effectiveMaterial.bind(world, this);
  20447. }
  20448. // Draw
  20449. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20450. // Unbind
  20451. effectiveMaterial.unbind();
  20452. // Outline - step 2
  20453. if (this.renderOutline && savedDepthWrite) {
  20454. engine.setDepthWrite(true);
  20455. engine.setColorWrite(false);
  20456. scene.getOutlineRenderer().render(subMesh, batch);
  20457. engine.setColorWrite(true);
  20458. }
  20459. // Overlay
  20460. if (this.renderOverlay) {
  20461. var currentMode = engine.getAlphaMode();
  20462. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20463. scene.getOutlineRenderer().render(subMesh, batch, true);
  20464. engine.setAlphaMode(currentMode);
  20465. }
  20466. this.onAfterRenderObservable.notifyObservers(this);
  20467. return this;
  20468. };
  20469. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20470. if (isInstance) {
  20471. effectiveMaterial.bindOnlyWorldMatrix(world);
  20472. }
  20473. return this;
  20474. };
  20475. /**
  20476. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20477. */
  20478. Mesh.prototype.getEmittedParticleSystems = function () {
  20479. var results = new Array();
  20480. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20481. var particleSystem = this.getScene().particleSystems[index];
  20482. if (particleSystem.emitter === this) {
  20483. results.push(particleSystem);
  20484. }
  20485. }
  20486. return results;
  20487. };
  20488. /**
  20489. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20490. */
  20491. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20492. var results = new Array();
  20493. var descendants = this.getDescendants();
  20494. descendants.push(this);
  20495. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20496. var particleSystem = this.getScene().particleSystems[index];
  20497. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20498. results.push(particleSystem);
  20499. }
  20500. }
  20501. return results;
  20502. };
  20503. Mesh.prototype._checkDelayState = function () {
  20504. var scene = this.getScene();
  20505. if (this._geometry) {
  20506. this._geometry.load(scene);
  20507. }
  20508. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20510. this._queueLoad(this, scene);
  20511. }
  20512. return this;
  20513. };
  20514. Mesh.prototype._queueLoad = function (mesh, scene) {
  20515. var _this = this;
  20516. scene._addPendingData(mesh);
  20517. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20518. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20519. if (data instanceof ArrayBuffer) {
  20520. _this._delayLoadingFunction(data, _this);
  20521. }
  20522. else {
  20523. _this._delayLoadingFunction(JSON.parse(data), _this);
  20524. }
  20525. _this.instances.forEach(function (instance) {
  20526. instance._syncSubMeshes();
  20527. });
  20528. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20529. scene._removePendingData(_this);
  20530. }, function () { }, scene.database, getBinaryData);
  20531. return this;
  20532. };
  20533. /**
  20534. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20535. */
  20536. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20537. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20538. return false;
  20539. }
  20540. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20541. return false;
  20542. }
  20543. this._checkDelayState();
  20544. return true;
  20545. };
  20546. /**
  20547. * Sets the mesh material by the material or multiMaterial `id` property.
  20548. * The material `id` is a string identifying the material or the multiMaterial.
  20549. * This method returns the Mesh.
  20550. */
  20551. Mesh.prototype.setMaterialByID = function (id) {
  20552. var materials = this.getScene().materials;
  20553. var index;
  20554. for (index = materials.length - 1; index > -1; index--) {
  20555. if (materials[index].id === id) {
  20556. this.material = materials[index];
  20557. return this;
  20558. }
  20559. }
  20560. // Multi
  20561. var multiMaterials = this.getScene().multiMaterials;
  20562. for (index = multiMaterials.length - 1; index > -1; index--) {
  20563. if (multiMaterials[index].id === id) {
  20564. this.material = multiMaterials[index];
  20565. return this;
  20566. }
  20567. }
  20568. return this;
  20569. };
  20570. /**
  20571. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20572. */
  20573. Mesh.prototype.getAnimatables = function () {
  20574. var results = [];
  20575. if (this.material) {
  20576. results.push(this.material);
  20577. }
  20578. if (this.skeleton) {
  20579. results.push(this.skeleton);
  20580. }
  20581. return results;
  20582. };
  20583. /**
  20584. * Modifies the mesh geometry according to the passed transformation matrix.
  20585. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20586. * The mesh normals are modified accordingly the same transformation.
  20587. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20588. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20589. * Returns the Mesh.
  20590. */
  20591. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20592. // Position
  20593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20594. return this;
  20595. }
  20596. var submeshes = this.subMeshes.splice(0);
  20597. this._resetPointsArrayCache();
  20598. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20599. var temp = [];
  20600. var index;
  20601. for (index = 0; index < data.length; index += 3) {
  20602. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20603. }
  20604. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20605. // Normals
  20606. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20607. return this;
  20608. }
  20609. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20610. temp = [];
  20611. for (index = 0; index < data.length; index += 3) {
  20612. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20613. }
  20614. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20615. // flip faces?
  20616. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20617. this.flipFaces();
  20618. }
  20619. // Restore submeshes
  20620. this.releaseSubMeshes();
  20621. this.subMeshes = submeshes;
  20622. return this;
  20623. };
  20624. /**
  20625. * Modifies the mesh geometry according to its own current World Matrix.
  20626. * The mesh World Matrix is then reset.
  20627. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20628. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20629. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20630. * Returns the Mesh.
  20631. */
  20632. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20633. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20634. this.scaling.copyFromFloats(1, 1, 1);
  20635. this.position.copyFromFloats(0, 0, 0);
  20636. this.rotation.copyFromFloats(0, 0, 0);
  20637. //only if quaternion is already set
  20638. if (this.rotationQuaternion) {
  20639. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20640. }
  20641. this._worldMatrix = BABYLON.Matrix.Identity();
  20642. return this;
  20643. };
  20644. Object.defineProperty(Mesh.prototype, "_positions", {
  20645. // Cache
  20646. get: function () {
  20647. if (this._geometry) {
  20648. return this._geometry._positions;
  20649. }
  20650. return null;
  20651. },
  20652. enumerable: true,
  20653. configurable: true
  20654. });
  20655. Mesh.prototype._resetPointsArrayCache = function () {
  20656. if (this._geometry) {
  20657. this._geometry._resetPointsArrayCache();
  20658. }
  20659. return this;
  20660. };
  20661. Mesh.prototype._generatePointsArray = function () {
  20662. if (this._geometry) {
  20663. return this._geometry._generatePointsArray();
  20664. }
  20665. return false;
  20666. };
  20667. /**
  20668. * Returns a new Mesh object generated from the current mesh properties.
  20669. * This method must not get confused with createInstance().
  20670. * The parameter `name` is a string, the name given to the new mesh.
  20671. * The optional parameter `newParent` can be any Node object (default `null`).
  20672. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20673. * 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.
  20674. */
  20675. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20676. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20677. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20678. };
  20679. /**
  20680. * Disposes the mesh.
  20681. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20682. */
  20683. Mesh.prototype.dispose = function (doNotRecurse) {
  20684. var _this = this;
  20685. this.morphTargetManager = undefined;
  20686. if (this._geometry) {
  20687. this._geometry.releaseForMesh(this, true);
  20688. }
  20689. // Sources
  20690. var meshes = this.getScene().meshes;
  20691. meshes.forEach(function (mesh) {
  20692. if (mesh._source && mesh._source === _this) {
  20693. mesh._source = null;
  20694. }
  20695. });
  20696. this._source = null;
  20697. // Instances
  20698. if (this._instancesBuffer) {
  20699. this._instancesBuffer.dispose();
  20700. this._instancesBuffer = null;
  20701. }
  20702. while (this.instances.length) {
  20703. this.instances[0].dispose();
  20704. }
  20705. // Highlight layers.
  20706. var highlightLayers = this.getScene().highlightLayers;
  20707. for (var i = 0; i < highlightLayers.length; i++) {
  20708. var highlightLayer = highlightLayers[i];
  20709. if (highlightLayer) {
  20710. highlightLayer.removeMesh(this);
  20711. highlightLayer.removeExcludedMesh(this);
  20712. }
  20713. }
  20714. _super.prototype.dispose.call(this, doNotRecurse);
  20715. };
  20716. /**
  20717. * Modifies the mesh geometry according to a displacement map.
  20718. * 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.
  20719. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20720. * This method returns nothing.
  20721. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20722. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20723. * 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.
  20724. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20725. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20726. *
  20727. * Returns the Mesh.
  20728. */
  20729. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20730. var _this = this;
  20731. var scene = this.getScene();
  20732. var onload = function (img) {
  20733. // Getting height map data
  20734. var canvas = document.createElement("canvas");
  20735. var context = canvas.getContext("2d");
  20736. var heightMapWidth = img.width;
  20737. var heightMapHeight = img.height;
  20738. canvas.width = heightMapWidth;
  20739. canvas.height = heightMapHeight;
  20740. context.drawImage(img, 0, 0);
  20741. // Create VertexData from map data
  20742. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20743. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20744. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20745. //execute success callback, if set
  20746. if (onSuccess) {
  20747. onSuccess(_this);
  20748. }
  20749. };
  20750. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20751. return this;
  20752. };
  20753. /**
  20754. * Modifies the mesh geometry according to a displacementMap buffer.
  20755. * 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.
  20756. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20757. * This method returns nothing.
  20758. * 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.
  20759. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20760. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20761. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20762. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20763. *
  20764. * Returns the Mesh.
  20765. */
  20766. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20767. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20768. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20769. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20770. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20771. return this;
  20772. }
  20773. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20774. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20775. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20776. var position = BABYLON.Vector3.Zero();
  20777. var normal = BABYLON.Vector3.Zero();
  20778. var uv = BABYLON.Vector2.Zero();
  20779. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20780. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20781. for (var index = 0; index < positions.length; index += 3) {
  20782. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20783. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20784. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20785. // Compute height
  20786. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20787. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20788. var pos = (u + v * heightMapWidth) * 4;
  20789. var r = buffer[pos] / 255.0;
  20790. var g = buffer[pos + 1] / 255.0;
  20791. var b = buffer[pos + 2] / 255.0;
  20792. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20793. normal.normalize();
  20794. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20795. position = position.add(normal);
  20796. position.toArray(positions, index);
  20797. }
  20798. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20799. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20800. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20801. return this;
  20802. };
  20803. /**
  20804. * Modify the mesh to get a flat shading rendering.
  20805. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20806. * This method returns the Mesh.
  20807. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20808. */
  20809. Mesh.prototype.convertToFlatShadedMesh = function () {
  20810. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20811. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20812. var kinds = this.getVerticesDataKinds();
  20813. var vbs = [];
  20814. var data = [];
  20815. var newdata = [];
  20816. var updatableNormals = false;
  20817. var kindIndex;
  20818. var kind;
  20819. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20820. kind = kinds[kindIndex];
  20821. var vertexBuffer = this.getVertexBuffer(kind);
  20822. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20823. updatableNormals = vertexBuffer.isUpdatable();
  20824. kinds.splice(kindIndex, 1);
  20825. kindIndex--;
  20826. continue;
  20827. }
  20828. vbs[kind] = vertexBuffer;
  20829. data[kind] = vbs[kind].getData();
  20830. newdata[kind] = [];
  20831. }
  20832. // Save previous submeshes
  20833. var previousSubmeshes = this.subMeshes.slice(0);
  20834. var indices = this.getIndices();
  20835. var totalIndices = this.getTotalIndices();
  20836. // Generating unique vertices per face
  20837. var index;
  20838. for (index = 0; index < totalIndices; index++) {
  20839. var vertexIndex = indices[index];
  20840. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20841. kind = kinds[kindIndex];
  20842. var stride = vbs[kind].getStrideSize();
  20843. for (var offset = 0; offset < stride; offset++) {
  20844. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20845. }
  20846. }
  20847. }
  20848. // Updating faces & normal
  20849. var normals = [];
  20850. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20851. for (index = 0; index < totalIndices; index += 3) {
  20852. indices[index] = index;
  20853. indices[index + 1] = index + 1;
  20854. indices[index + 2] = index + 2;
  20855. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20856. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20857. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20858. var p1p2 = p1.subtract(p2);
  20859. var p3p2 = p3.subtract(p2);
  20860. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20861. // Store same normals for every vertex
  20862. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20863. normals.push(normal.x);
  20864. normals.push(normal.y);
  20865. normals.push(normal.z);
  20866. }
  20867. }
  20868. this.setIndices(indices);
  20869. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20870. // Updating vertex buffers
  20871. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20872. kind = kinds[kindIndex];
  20873. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20874. }
  20875. // Updating submeshes
  20876. this.releaseSubMeshes();
  20877. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20878. var previousOne = previousSubmeshes[submeshIndex];
  20879. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20880. }
  20881. this.synchronizeInstances();
  20882. return this;
  20883. };
  20884. /**
  20885. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20886. * In other words, more vertices, no more indices and a single bigger VBO.
  20887. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20888. * Returns the Mesh.
  20889. */
  20890. Mesh.prototype.convertToUnIndexedMesh = function () {
  20891. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20892. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20893. var kinds = this.getVerticesDataKinds();
  20894. var vbs = [];
  20895. var data = [];
  20896. var newdata = [];
  20897. var updatableNormals = false;
  20898. var kindIndex;
  20899. var kind;
  20900. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20901. kind = kinds[kindIndex];
  20902. var vertexBuffer = this.getVertexBuffer(kind);
  20903. vbs[kind] = vertexBuffer;
  20904. data[kind] = vbs[kind].getData();
  20905. newdata[kind] = [];
  20906. }
  20907. // Save previous submeshes
  20908. var previousSubmeshes = this.subMeshes.slice(0);
  20909. var indices = this.getIndices();
  20910. var totalIndices = this.getTotalIndices();
  20911. // Generating unique vertices per face
  20912. var index;
  20913. for (index = 0; index < totalIndices; index++) {
  20914. var vertexIndex = indices[index];
  20915. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20916. kind = kinds[kindIndex];
  20917. var stride = vbs[kind].getStrideSize();
  20918. for (var offset = 0; offset < stride; offset++) {
  20919. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20920. }
  20921. }
  20922. }
  20923. // Updating indices
  20924. for (index = 0; index < totalIndices; index += 3) {
  20925. indices[index] = index;
  20926. indices[index + 1] = index + 1;
  20927. indices[index + 2] = index + 2;
  20928. }
  20929. this.setIndices(indices);
  20930. // Updating vertex buffers
  20931. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20932. kind = kinds[kindIndex];
  20933. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20934. }
  20935. // Updating submeshes
  20936. this.releaseSubMeshes();
  20937. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20938. var previousOne = previousSubmeshes[submeshIndex];
  20939. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20940. }
  20941. this._unIndexed = true;
  20942. this.synchronizeInstances();
  20943. return this;
  20944. };
  20945. /**
  20946. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20947. * This method returns the Mesh.
  20948. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20949. */
  20950. Mesh.prototype.flipFaces = function (flipNormals) {
  20951. if (flipNormals === void 0) { flipNormals = false; }
  20952. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20953. var i;
  20954. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20955. for (i = 0; i < vertex_data.normals.length; i++) {
  20956. vertex_data.normals[i] *= -1;
  20957. }
  20958. }
  20959. var temp;
  20960. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20961. // reassign indices
  20962. temp = vertex_data.indices[i + 1];
  20963. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20964. vertex_data.indices[i + 2] = temp;
  20965. }
  20966. vertex_data.applyToMesh(this);
  20967. return this;
  20968. };
  20969. // Instances
  20970. /**
  20971. * Creates a new InstancedMesh object from the mesh model.
  20972. * An instance shares the same properties and the same material than its model.
  20973. * Only these properties of each instance can then be set individually :
  20974. * - position
  20975. * - rotation
  20976. * - rotationQuaternion
  20977. * - setPivotMatrix
  20978. * - scaling
  20979. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20980. * Warning : this method is not supported for Line mesh and LineSystem
  20981. */
  20982. Mesh.prototype.createInstance = function (name) {
  20983. return new BABYLON.InstancedMesh(name, this);
  20984. };
  20985. /**
  20986. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20987. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20988. * This method returns the Mesh.
  20989. */
  20990. Mesh.prototype.synchronizeInstances = function () {
  20991. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20992. var instance = this.instances[instanceIndex];
  20993. instance._syncSubMeshes();
  20994. }
  20995. return this;
  20996. };
  20997. /**
  20998. * Simplify the mesh according to the given array of settings.
  20999. * Function will return immediately and will simplify async. It returns the Mesh.
  21000. * @param settings a collection of simplification settings.
  21001. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21002. * @param type the type of simplification to run.
  21003. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21004. */
  21005. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21006. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21007. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21008. this.getScene().simplificationQueue.addTask({
  21009. settings: settings,
  21010. parallelProcessing: parallelProcessing,
  21011. mesh: this,
  21012. simplificationType: simplificationType,
  21013. successCallback: successCallback
  21014. });
  21015. return this;
  21016. };
  21017. /**
  21018. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21019. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21020. * This should be used together with the simplification to avoid disappearing triangles.
  21021. * Returns the Mesh.
  21022. * @param successCallback an optional success callback to be called after the optimization finished.
  21023. */
  21024. Mesh.prototype.optimizeIndices = function (successCallback) {
  21025. var _this = this;
  21026. var indices = this.getIndices();
  21027. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21028. var vectorPositions = [];
  21029. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21030. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21031. }
  21032. var dupes = [];
  21033. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21034. var realPos = vectorPositions.length - 1 - iteration;
  21035. var testedPosition = vectorPositions[realPos];
  21036. for (var j = 0; j < realPos; ++j) {
  21037. var againstPosition = vectorPositions[j];
  21038. if (testedPosition.equals(againstPosition)) {
  21039. dupes[realPos] = j;
  21040. break;
  21041. }
  21042. }
  21043. }, function () {
  21044. for (var i = 0; i < indices.length; ++i) {
  21045. indices[i] = dupes[indices[i]] || indices[i];
  21046. }
  21047. //indices are now reordered
  21048. var originalSubMeshes = _this.subMeshes.slice(0);
  21049. _this.setIndices(indices);
  21050. _this.subMeshes = originalSubMeshes;
  21051. if (successCallback) {
  21052. successCallback(_this);
  21053. }
  21054. });
  21055. return this;
  21056. };
  21057. Mesh.prototype.serialize = function (serializationObject) {
  21058. serializationObject.name = this.name;
  21059. serializationObject.id = this.id;
  21060. serializationObject.type = this.getClassName();
  21061. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21062. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21063. }
  21064. serializationObject.position = this.position.asArray();
  21065. if (this.rotationQuaternion) {
  21066. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21067. }
  21068. else if (this.rotation) {
  21069. serializationObject.rotation = this.rotation.asArray();
  21070. }
  21071. serializationObject.scaling = this.scaling.asArray();
  21072. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21073. serializationObject.isEnabled = this.isEnabled();
  21074. serializationObject.isVisible = this.isVisible;
  21075. serializationObject.infiniteDistance = this.infiniteDistance;
  21076. serializationObject.pickable = this.isPickable;
  21077. serializationObject.receiveShadows = this.receiveShadows;
  21078. serializationObject.billboardMode = this.billboardMode;
  21079. serializationObject.visibility = this.visibility;
  21080. serializationObject.checkCollisions = this.checkCollisions;
  21081. serializationObject.isBlocker = this.isBlocker;
  21082. // Parent
  21083. if (this.parent) {
  21084. serializationObject.parentId = this.parent.id;
  21085. }
  21086. // Geometry
  21087. var geometry = this._geometry;
  21088. if (geometry) {
  21089. var geometryId = geometry.id;
  21090. serializationObject.geometryId = geometryId;
  21091. // SubMeshes
  21092. serializationObject.subMeshes = [];
  21093. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21094. var subMesh = this.subMeshes[subIndex];
  21095. serializationObject.subMeshes.push({
  21096. materialIndex: subMesh.materialIndex,
  21097. verticesStart: subMesh.verticesStart,
  21098. verticesCount: subMesh.verticesCount,
  21099. indexStart: subMesh.indexStart,
  21100. indexCount: subMesh.indexCount
  21101. });
  21102. }
  21103. }
  21104. // Material
  21105. if (this.material) {
  21106. serializationObject.materialId = this.material.id;
  21107. }
  21108. else {
  21109. this.material = null;
  21110. }
  21111. // Morph targets
  21112. if (this.morphTargetManager) {
  21113. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21114. }
  21115. // Skeleton
  21116. if (this.skeleton) {
  21117. serializationObject.skeletonId = this.skeleton.id;
  21118. }
  21119. // Physics
  21120. //TODO implement correct serialization for physics impostors.
  21121. if (this.getPhysicsImpostor()) {
  21122. var impostor = this.getPhysicsImpostor();
  21123. serializationObject.physicsMass = impostor.getParam("mass");
  21124. serializationObject.physicsFriction = impostor.getParam("friction");
  21125. serializationObject.physicsRestitution = impostor.getParam("mass");
  21126. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21127. }
  21128. // Metadata
  21129. if (this.metadata) {
  21130. serializationObject.metadata = this.metadata;
  21131. }
  21132. // Instances
  21133. serializationObject.instances = [];
  21134. for (var index = 0; index < this.instances.length; index++) {
  21135. var instance = this.instances[index];
  21136. var serializationInstance = {
  21137. name: instance.name,
  21138. position: instance.position.asArray(),
  21139. scaling: instance.scaling.asArray()
  21140. };
  21141. if (instance.rotationQuaternion) {
  21142. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21143. }
  21144. else if (instance.rotation) {
  21145. serializationInstance.rotation = instance.rotation.asArray();
  21146. }
  21147. serializationObject.instances.push(serializationInstance);
  21148. // Animations
  21149. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21150. serializationInstance.ranges = instance.serializeAnimationRanges();
  21151. }
  21152. //
  21153. // Animations
  21154. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21155. serializationObject.ranges = this.serializeAnimationRanges();
  21156. // Layer mask
  21157. serializationObject.layerMask = this.layerMask;
  21158. // Alpha
  21159. serializationObject.alphaIndex = this.alphaIndex;
  21160. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21161. // Overlay
  21162. serializationObject.overlayAlpha = this.overlayAlpha;
  21163. serializationObject.overlayColor = this.overlayColor.asArray();
  21164. serializationObject.renderOverlay = this.renderOverlay;
  21165. // Fog
  21166. serializationObject.applyFog = this.applyFog;
  21167. // Action Manager
  21168. if (this.actionManager) {
  21169. serializationObject.actions = this.actionManager.serialize(this.name);
  21170. }
  21171. };
  21172. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21173. if (!this.geometry) {
  21174. return;
  21175. }
  21176. this._markSubMeshesAsAttributesDirty();
  21177. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21178. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21179. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21180. this.morphTargetManager = undefined;
  21181. return;
  21182. }
  21183. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21184. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21185. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21186. if (morphTarget.hasNormals) {
  21187. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21188. }
  21189. if (morphTarget.hasTangents) {
  21190. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21191. }
  21192. }
  21193. }
  21194. else {
  21195. var index = 0;
  21196. // Positions
  21197. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21198. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21199. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21200. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21201. }
  21202. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21203. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21204. }
  21205. index++;
  21206. }
  21207. }
  21208. };
  21209. // Statics
  21210. /**
  21211. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21212. * The parameter `parsedMesh` is the mesh to be copied.
  21213. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21214. */
  21215. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21216. var mesh;
  21217. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21218. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21219. }
  21220. else {
  21221. mesh = new Mesh(parsedMesh.name, scene);
  21222. }
  21223. mesh.id = parsedMesh.id;
  21224. if (BABYLON.Tags) {
  21225. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21226. }
  21227. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21228. if (parsedMesh.metadata !== undefined) {
  21229. mesh.metadata = parsedMesh.metadata;
  21230. }
  21231. if (parsedMesh.rotationQuaternion) {
  21232. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21233. }
  21234. else if (parsedMesh.rotation) {
  21235. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21236. }
  21237. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21238. if (parsedMesh.localMatrix) {
  21239. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21240. }
  21241. else if (parsedMesh.pivotMatrix) {
  21242. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21243. }
  21244. mesh.setEnabled(parsedMesh.isEnabled);
  21245. mesh.isVisible = parsedMesh.isVisible;
  21246. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21247. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21248. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21249. if (parsedMesh.applyFog !== undefined) {
  21250. mesh.applyFog = parsedMesh.applyFog;
  21251. }
  21252. if (parsedMesh.pickable !== undefined) {
  21253. mesh.isPickable = parsedMesh.pickable;
  21254. }
  21255. if (parsedMesh.alphaIndex !== undefined) {
  21256. mesh.alphaIndex = parsedMesh.alphaIndex;
  21257. }
  21258. mesh.receiveShadows = parsedMesh.receiveShadows;
  21259. mesh.billboardMode = parsedMesh.billboardMode;
  21260. if (parsedMesh.visibility !== undefined) {
  21261. mesh.visibility = parsedMesh.visibility;
  21262. }
  21263. mesh.checkCollisions = parsedMesh.checkCollisions;
  21264. if (parsedMesh.isBlocker !== undefined) {
  21265. mesh.isBlocker = parsedMesh.isBlocker;
  21266. }
  21267. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21268. // freezeWorldMatrix
  21269. if (parsedMesh.freezeWorldMatrix) {
  21270. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21271. }
  21272. // Parent
  21273. if (parsedMesh.parentId) {
  21274. mesh._waitingParentId = parsedMesh.parentId;
  21275. }
  21276. // Actions
  21277. if (parsedMesh.actions !== undefined) {
  21278. mesh._waitingActions = parsedMesh.actions;
  21279. }
  21280. // Overlay
  21281. if (parsedMesh.overlayAlpha !== undefined) {
  21282. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21283. }
  21284. if (parsedMesh.overlayColor !== undefined) {
  21285. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21286. }
  21287. if (parsedMesh.renderOverlay !== undefined) {
  21288. mesh.renderOverlay = parsedMesh.renderOverlay;
  21289. }
  21290. // Geometry
  21291. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21292. if (parsedMesh.delayLoadingFile) {
  21293. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21294. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21295. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21296. if (parsedMesh._binaryInfo) {
  21297. mesh._binaryInfo = parsedMesh._binaryInfo;
  21298. }
  21299. mesh._delayInfo = [];
  21300. if (parsedMesh.hasUVs) {
  21301. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21302. }
  21303. if (parsedMesh.hasUVs2) {
  21304. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21305. }
  21306. if (parsedMesh.hasUVs3) {
  21307. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21308. }
  21309. if (parsedMesh.hasUVs4) {
  21310. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21311. }
  21312. if (parsedMesh.hasUVs5) {
  21313. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21314. }
  21315. if (parsedMesh.hasUVs6) {
  21316. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21317. }
  21318. if (parsedMesh.hasColors) {
  21319. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21320. }
  21321. if (parsedMesh.hasMatricesIndices) {
  21322. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21323. }
  21324. if (parsedMesh.hasMatricesWeights) {
  21325. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21326. }
  21327. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21328. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21329. mesh._checkDelayState();
  21330. }
  21331. }
  21332. else {
  21333. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21334. }
  21335. // Material
  21336. if (parsedMesh.materialId) {
  21337. mesh.setMaterialByID(parsedMesh.materialId);
  21338. }
  21339. else {
  21340. mesh.material = null;
  21341. }
  21342. // Morph targets
  21343. if (parsedMesh.morphTargetManagerId > -1) {
  21344. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21345. }
  21346. // Skeleton
  21347. if (parsedMesh.skeletonId > -1) {
  21348. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21349. if (parsedMesh.numBoneInfluencers) {
  21350. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21351. }
  21352. }
  21353. // Animations
  21354. if (parsedMesh.animations) {
  21355. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21356. var parsedAnimation = parsedMesh.animations[animationIndex];
  21357. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21358. }
  21359. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21360. }
  21361. if (parsedMesh.autoAnimate) {
  21362. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21363. }
  21364. // Layer Mask
  21365. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21366. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21367. }
  21368. else {
  21369. mesh.layerMask = 0x0FFFFFFF;
  21370. }
  21371. // Physics
  21372. if (parsedMesh.physicsImpostor) {
  21373. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21374. mass: parsedMesh.physicsMass,
  21375. friction: parsedMesh.physicsFriction,
  21376. restitution: parsedMesh.physicsRestitution
  21377. }, scene);
  21378. }
  21379. // Instances
  21380. if (parsedMesh.instances) {
  21381. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21382. var parsedInstance = parsedMesh.instances[index];
  21383. var instance = mesh.createInstance(parsedInstance.name);
  21384. if (BABYLON.Tags) {
  21385. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21386. }
  21387. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21388. if (parsedInstance.parentId) {
  21389. instance._waitingParentId = parsedInstance.parentId;
  21390. }
  21391. if (parsedInstance.rotationQuaternion) {
  21392. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21393. }
  21394. else if (parsedInstance.rotation) {
  21395. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21396. }
  21397. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21398. instance.checkCollisions = mesh.checkCollisions;
  21399. if (parsedMesh.animations) {
  21400. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21401. parsedAnimation = parsedMesh.animations[animationIndex];
  21402. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21403. }
  21404. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21405. }
  21406. }
  21407. }
  21408. return mesh;
  21409. };
  21410. /**
  21411. * Creates a ribbon mesh.
  21412. * Please consider using the same method from the MeshBuilder class instead.
  21413. * 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.
  21414. *
  21415. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21416. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21417. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21418. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21419. * 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.
  21420. * 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.
  21421. * 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
  21422. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21425. */
  21426. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21427. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21428. pathArray: pathArray,
  21429. closeArray: closeArray,
  21430. closePath: closePath,
  21431. offset: offset,
  21432. updatable: updatable,
  21433. sideOrientation: sideOrientation,
  21434. instance: instance
  21435. }, scene);
  21436. };
  21437. /**
  21438. * Creates a plane polygonal mesh. By default, this is a disc.
  21439. * Please consider using the same method from the MeshBuilder class instead.
  21440. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21441. * 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.
  21442. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21443. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21445. */
  21446. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21447. var options = {
  21448. radius: radius,
  21449. tessellation: tessellation,
  21450. sideOrientation: sideOrientation,
  21451. updatable: updatable
  21452. };
  21453. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21454. };
  21455. /**
  21456. * Creates a box mesh.
  21457. * Please consider using the same method from the MeshBuilder class instead.
  21458. * The parameter `size` sets the size (float) of each box side (default 1).
  21459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21462. */
  21463. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21464. var options = {
  21465. size: size,
  21466. sideOrientation: sideOrientation,
  21467. updatable: updatable
  21468. };
  21469. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21470. };
  21471. /**
  21472. * Creates a sphere mesh.
  21473. * Please consider using the same method from the MeshBuilder class instead.
  21474. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21475. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21479. */
  21480. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21481. var options = {
  21482. segments: segments,
  21483. diameterX: diameter,
  21484. diameterY: diameter,
  21485. diameterZ: diameter,
  21486. sideOrientation: sideOrientation,
  21487. updatable: updatable
  21488. };
  21489. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21490. };
  21491. /**
  21492. * Creates a cylinder or a cone mesh.
  21493. * Please consider using the same method from the MeshBuilder class instead.
  21494. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21495. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21496. * 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.
  21497. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21498. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21500. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21502. */
  21503. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21504. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21505. if (scene !== undefined) {
  21506. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21507. updatable = scene;
  21508. }
  21509. scene = subdivisions;
  21510. subdivisions = 1;
  21511. }
  21512. var options = {
  21513. height: height,
  21514. diameterTop: diameterTop,
  21515. diameterBottom: diameterBottom,
  21516. tessellation: tessellation,
  21517. subdivisions: subdivisions,
  21518. sideOrientation: sideOrientation,
  21519. updatable: updatable
  21520. };
  21521. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21522. };
  21523. // Torus (Code from SharpDX.org)
  21524. /**
  21525. * Creates a torus mesh.
  21526. * Please consider using the same method from the MeshBuilder class instead.
  21527. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21528. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21529. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21533. */
  21534. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21535. var options = {
  21536. diameter: diameter,
  21537. thickness: thickness,
  21538. tessellation: tessellation,
  21539. sideOrientation: sideOrientation,
  21540. updatable: updatable
  21541. };
  21542. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21543. };
  21544. /**
  21545. * Creates a torus knot mesh.
  21546. * Please consider using the same method from the MeshBuilder class instead.
  21547. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21548. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21549. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21550. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21551. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21552. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21553. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21554. */
  21555. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21556. var options = {
  21557. radius: radius,
  21558. tube: tube,
  21559. radialSegments: radialSegments,
  21560. tubularSegments: tubularSegments,
  21561. p: p,
  21562. q: q,
  21563. sideOrientation: sideOrientation,
  21564. updatable: updatable
  21565. };
  21566. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21567. };
  21568. /**
  21569. * Creates a line mesh.
  21570. * Please consider using the same method from the MeshBuilder class instead.
  21571. * 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.
  21572. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21573. * The parameter `points` is an array successive Vector3.
  21574. * 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
  21575. * When updating an instance, remember that only point positions can change, not the number of points.
  21576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21577. */
  21578. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21579. var options = {
  21580. points: points,
  21581. updatable: updatable,
  21582. instance: instance
  21583. };
  21584. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21585. };
  21586. /**
  21587. * Creates a dashed line mesh.
  21588. * Please consider using the same method from the MeshBuilder class instead.
  21589. * 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.
  21590. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21591. * The parameter `points` is an array successive Vector3.
  21592. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21593. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21594. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21595. * 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
  21596. * When updating an instance, remember that only point positions can change, not the number of points.
  21597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21598. */
  21599. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21600. var options = {
  21601. points: points,
  21602. dashSize: dashSize,
  21603. gapSize: gapSize,
  21604. dashNb: dashNb,
  21605. updatable: updatable,
  21606. instance: instance
  21607. };
  21608. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21609. };
  21610. /**
  21611. * Creates a polygon mesh.
  21612. * Please consider using the same method from the MeshBuilder class instead.
  21613. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21614. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  21615. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21616. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21617. * Remember you can only change the shape positions, not their number when updating a polygon.
  21618. */
  21619. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21620. var options = {
  21621. shape: shape,
  21622. holes: holes,
  21623. updatable: updatable,
  21624. sideOrientation: sideOrientation
  21625. };
  21626. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21627. };
  21628. /**
  21629. * Creates an extruded polygon mesh, with depth in the Y direction.
  21630. * Please consider using the same method from the MeshBuilder class instead.
  21631. */
  21632. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21633. var options = {
  21634. shape: shape,
  21635. holes: holes,
  21636. depth: depth,
  21637. updatable: updatable,
  21638. sideOrientation: sideOrientation
  21639. };
  21640. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21641. };
  21642. /**
  21643. * Creates an extruded shape mesh.
  21644. * 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.
  21645. * Please consider using the same method from the MeshBuilder class instead.
  21646. *
  21647. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21648. * 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
  21649. * extruded along the Z axis.
  21650. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21651. * 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.
  21652. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21653. * 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
  21654. * 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
  21655. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21656. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21657. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21659. */
  21660. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21661. var options = {
  21662. shape: shape,
  21663. path: path,
  21664. scale: scale,
  21665. rotation: rotation,
  21666. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21667. sideOrientation: sideOrientation,
  21668. instance: instance,
  21669. updatable: updatable
  21670. };
  21671. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21672. };
  21673. /**
  21674. * Creates an custom extruded shape mesh.
  21675. * 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.
  21676. * Please consider using the same method from the MeshBuilder class instead.
  21677. *
  21678. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21679. * 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
  21680. * extruded along the Z axis.
  21681. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21682. * 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
  21683. * and the distance of this point from the begining of the path :
  21684. * ```javascript
  21685. * var rotationFunction = function(i, distance) {
  21686. * // do things
  21687. * return rotationValue; }
  21688. * ```
  21689. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21690. * 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
  21691. * and the distance of this point from the begining of the path :
  21692. * ```javascript
  21693. * var scaleFunction = function(i, distance) {
  21694. * // do things
  21695. * return scaleValue;}
  21696. * ```
  21697. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21698. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21699. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21700. * 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
  21701. * 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
  21702. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21703. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21704. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21705. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21706. */
  21707. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21708. var options = {
  21709. shape: shape,
  21710. path: path,
  21711. scaleFunction: scaleFunction,
  21712. rotationFunction: rotationFunction,
  21713. ribbonCloseArray: ribbonCloseArray,
  21714. ribbonClosePath: ribbonClosePath,
  21715. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21716. sideOrientation: sideOrientation,
  21717. instance: instance,
  21718. updatable: updatable
  21719. };
  21720. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21721. };
  21722. /**
  21723. * Creates lathe mesh.
  21724. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21725. * Please consider using the same method from the MeshBuilder class instead.
  21726. * 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
  21727. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21728. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21729. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21733. */
  21734. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21735. var options = {
  21736. shape: shape,
  21737. radius: radius,
  21738. tessellation: tessellation,
  21739. sideOrientation: sideOrientation,
  21740. updatable: updatable
  21741. };
  21742. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21743. };
  21744. /**
  21745. * Creates a plane mesh.
  21746. * Please consider using the same method from the MeshBuilder class instead.
  21747. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21749. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21751. */
  21752. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21753. var options = {
  21754. size: size,
  21755. width: size,
  21756. height: size,
  21757. sideOrientation: sideOrientation,
  21758. updatable: updatable
  21759. };
  21760. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21761. };
  21762. /**
  21763. * Creates a ground mesh.
  21764. * Please consider using the same method from the MeshBuilder class instead.
  21765. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21766. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21768. */
  21769. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21770. var options = {
  21771. width: width,
  21772. height: height,
  21773. subdivisions: subdivisions,
  21774. updatable: updatable
  21775. };
  21776. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21777. };
  21778. /**
  21779. * Creates a tiled ground mesh.
  21780. * Please consider using the same method from the MeshBuilder class instead.
  21781. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21782. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21783. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21784. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21785. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21786. * numbers of subdivisions on the ground width and height of each tile.
  21787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21788. */
  21789. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21790. var options = {
  21791. xmin: xmin,
  21792. zmin: zmin,
  21793. xmax: xmax,
  21794. zmax: zmax,
  21795. subdivisions: subdivisions,
  21796. precision: precision,
  21797. updatable: updatable
  21798. };
  21799. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21800. };
  21801. /**
  21802. * Creates a ground mesh from a height map.
  21803. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21804. * Please consider using the same method from the MeshBuilder class instead.
  21805. * The parameter `url` sets the URL of the height map image resource.
  21806. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21807. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21808. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21809. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21810. * 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).
  21811. * This function is passed the newly built mesh :
  21812. * ```javascript
  21813. * function(mesh) { // do things
  21814. * return; }
  21815. * ```
  21816. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21817. */
  21818. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21819. var options = {
  21820. width: width,
  21821. height: height,
  21822. subdivisions: subdivisions,
  21823. minHeight: minHeight,
  21824. maxHeight: maxHeight,
  21825. updatable: updatable,
  21826. onReady: onReady
  21827. };
  21828. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21829. };
  21830. /**
  21831. * Creates a tube mesh.
  21832. * 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.
  21833. * Please consider using the same method from the MeshBuilder class instead.
  21834. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21835. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21836. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21837. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21838. * 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.
  21839. * It must return a radius value (positive float) :
  21840. * ```javascript
  21841. * var radiusFunction = function(i, distance) {
  21842. * // do things
  21843. * return radius; }
  21844. * ```
  21845. * 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
  21846. * 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
  21847. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21849. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21850. */
  21851. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21852. var options = {
  21853. path: path,
  21854. radius: radius,
  21855. tessellation: tessellation,
  21856. radiusFunction: radiusFunction,
  21857. arc: 1,
  21858. cap: cap,
  21859. updatable: updatable,
  21860. sideOrientation: sideOrientation,
  21861. instance: instance
  21862. };
  21863. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21864. };
  21865. /**
  21866. * Creates a polyhedron mesh.
  21867. * Please consider using the same method from the MeshBuilder class instead.
  21868. * 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
  21869. * to choose the wanted type.
  21870. * The parameter `size` (positive float, default 1) sets the polygon size.
  21871. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21872. * 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`.
  21873. * 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
  21874. * 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)`).
  21875. * 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
  21876. * 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.
  21877. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21878. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21880. */
  21881. Mesh.CreatePolyhedron = function (name, options, scene) {
  21882. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21883. };
  21884. /**
  21885. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21886. * Please consider using the same method from the MeshBuilder class instead.
  21887. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21888. * 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`).
  21889. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21890. * 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.
  21891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21894. */
  21895. Mesh.CreateIcoSphere = function (name, options, scene) {
  21896. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21897. };
  21898. /**
  21899. * Creates a decal mesh.
  21900. * Please consider using the same method from the MeshBuilder class instead.
  21901. * 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.
  21902. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21903. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21904. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21905. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21906. */
  21907. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21908. var options = {
  21909. position: position,
  21910. normal: normal,
  21911. size: size,
  21912. angle: angle
  21913. };
  21914. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21915. };
  21916. // Skeletons
  21917. /**
  21918. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21919. */
  21920. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21921. var source;
  21922. if (!this._sourcePositions) {
  21923. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21924. this._sourcePositions = new Float32Array(source);
  21925. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21926. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21927. }
  21928. }
  21929. return this._sourcePositions;
  21930. };
  21931. /**
  21932. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21933. */
  21934. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21935. var source;
  21936. if (!this._sourceNormals) {
  21937. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21938. this._sourceNormals = new Float32Array(source);
  21939. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21940. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21941. }
  21942. }
  21943. return this._sourceNormals;
  21944. };
  21945. /**
  21946. * Updates the vertex buffer by applying transformation from the bones.
  21947. * Returns the Mesh.
  21948. *
  21949. * @param {skeleton} skeleton to apply
  21950. */
  21951. Mesh.prototype.applySkeleton = function (skeleton) {
  21952. if (!this.geometry) {
  21953. return this;
  21954. }
  21955. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21956. return this;
  21957. }
  21958. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21959. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21960. return this;
  21961. }
  21962. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21963. return this;
  21964. }
  21965. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21966. return this;
  21967. }
  21968. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21969. return this;
  21970. }
  21971. if (!this._sourcePositions) {
  21972. var submeshes = this.subMeshes.slice();
  21973. this.setPositionsForCPUSkinning();
  21974. this.subMeshes = submeshes;
  21975. }
  21976. if (!this._sourceNormals) {
  21977. this.setNormalsForCPUSkinning();
  21978. }
  21979. // positionsData checks for not being Float32Array will only pass at most once
  21980. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21981. if (!(positionsData instanceof Float32Array)) {
  21982. positionsData = new Float32Array(positionsData);
  21983. }
  21984. // normalsData checks for not being Float32Array will only pass at most once
  21985. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21986. if (!(normalsData instanceof Float32Array)) {
  21987. normalsData = new Float32Array(normalsData);
  21988. }
  21989. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21990. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21991. var needExtras = this.numBoneInfluencers > 4;
  21992. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21993. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21994. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21995. var tempVector3 = BABYLON.Vector3.Zero();
  21996. var finalMatrix = new BABYLON.Matrix();
  21997. var tempMatrix = new BABYLON.Matrix();
  21998. var matWeightIdx = 0;
  21999. var inf;
  22000. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22001. var weight;
  22002. for (inf = 0; inf < 4; inf++) {
  22003. weight = matricesWeightsData[matWeightIdx + inf];
  22004. if (weight > 0) {
  22005. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22006. finalMatrix.addToSelf(tempMatrix);
  22007. }
  22008. else
  22009. break;
  22010. }
  22011. if (needExtras) {
  22012. for (inf = 0; inf < 4; inf++) {
  22013. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22014. if (weight > 0) {
  22015. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22016. finalMatrix.addToSelf(tempMatrix);
  22017. }
  22018. else
  22019. break;
  22020. }
  22021. }
  22022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22023. tempVector3.toArray(positionsData, index);
  22024. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22025. tempVector3.toArray(normalsData, index);
  22026. finalMatrix.reset();
  22027. }
  22028. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22029. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22030. return this;
  22031. };
  22032. // Tools
  22033. /**
  22034. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22035. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22036. */
  22037. Mesh.MinMax = function (meshes) {
  22038. var minVector = null;
  22039. var maxVector = null;
  22040. meshes.forEach(function (mesh, index, array) {
  22041. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22042. if (!minVector) {
  22043. minVector = boundingBox.minimumWorld;
  22044. maxVector = boundingBox.maximumWorld;
  22045. }
  22046. else {
  22047. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22048. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22049. }
  22050. });
  22051. return {
  22052. min: minVector,
  22053. max: maxVector
  22054. };
  22055. };
  22056. /**
  22057. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22058. */
  22059. Mesh.Center = function (meshesOrMinMaxVector) {
  22060. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22061. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22062. };
  22063. /**
  22064. * Merge the array of meshes into a single mesh for performance reasons.
  22065. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22066. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22067. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22068. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22069. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22070. */
  22071. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22072. if (disposeSource === void 0) { disposeSource = true; }
  22073. var index;
  22074. if (!allow32BitsIndices) {
  22075. var totalVertices = 0;
  22076. // Counting vertices
  22077. for (index = 0; index < meshes.length; index++) {
  22078. if (meshes[index]) {
  22079. totalVertices += meshes[index].getTotalVertices();
  22080. if (totalVertices > 65536) {
  22081. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22082. return null;
  22083. }
  22084. }
  22085. }
  22086. }
  22087. // Merge
  22088. var vertexData;
  22089. var otherVertexData;
  22090. var indiceArray = new Array();
  22091. var source;
  22092. for (index = 0; index < meshes.length; index++) {
  22093. if (meshes[index]) {
  22094. meshes[index].computeWorldMatrix(true);
  22095. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22096. otherVertexData.transform(meshes[index].getWorldMatrix());
  22097. if (vertexData) {
  22098. vertexData.merge(otherVertexData);
  22099. }
  22100. else {
  22101. vertexData = otherVertexData;
  22102. source = meshes[index];
  22103. }
  22104. if (subdivideWithSubMeshes) {
  22105. indiceArray.push(meshes[index].getTotalIndices());
  22106. }
  22107. }
  22108. }
  22109. if (!meshSubclass) {
  22110. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22111. }
  22112. vertexData.applyToMesh(meshSubclass);
  22113. // Setting properties
  22114. meshSubclass.material = source.material;
  22115. meshSubclass.checkCollisions = source.checkCollisions;
  22116. // Cleaning
  22117. if (disposeSource) {
  22118. for (index = 0; index < meshes.length; index++) {
  22119. if (meshes[index]) {
  22120. meshes[index].dispose();
  22121. }
  22122. }
  22123. }
  22124. // Subdivide
  22125. if (subdivideWithSubMeshes) {
  22126. //-- Suppresions du submesh global
  22127. meshSubclass.releaseSubMeshes();
  22128. index = 0;
  22129. var offset = 0;
  22130. //-- aplique la subdivision en fonction du tableau d'indices
  22131. while (index < indiceArray.length) {
  22132. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22133. offset += indiceArray[index];
  22134. index++;
  22135. }
  22136. }
  22137. return meshSubclass;
  22138. };
  22139. return Mesh;
  22140. }(BABYLON.AbstractMesh));
  22141. // Consts
  22142. Mesh._FRONTSIDE = 0;
  22143. Mesh._BACKSIDE = 1;
  22144. Mesh._DOUBLESIDE = 2;
  22145. Mesh._DEFAULTSIDE = 0;
  22146. Mesh._NO_CAP = 0;
  22147. Mesh._CAP_START = 1;
  22148. Mesh._CAP_END = 2;
  22149. Mesh._CAP_ALL = 3;
  22150. BABYLON.Mesh = Mesh;
  22151. })(BABYLON || (BABYLON = {}));
  22152. //# sourceMappingURL=babylon.mesh.js.map
  22153. var BABYLON;
  22154. (function (BABYLON) {
  22155. var SubMesh = (function () {
  22156. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22157. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22158. this.materialIndex = materialIndex;
  22159. this.verticesStart = verticesStart;
  22160. this.verticesCount = verticesCount;
  22161. this.indexStart = indexStart;
  22162. this.indexCount = indexCount;
  22163. this._renderId = 0;
  22164. this._mesh = mesh;
  22165. this._renderingMesh = renderingMesh || mesh;
  22166. mesh.subMeshes.push(this);
  22167. this._trianglePlanes = [];
  22168. this._id = mesh.subMeshes.length - 1;
  22169. if (createBoundingBox) {
  22170. this.refreshBoundingInfo();
  22171. mesh.computeWorldMatrix(true);
  22172. }
  22173. }
  22174. Object.defineProperty(SubMesh.prototype, "effect", {
  22175. get: function () {
  22176. return this._materialEffect;
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. SubMesh.prototype.setEffect = function (effect, defines) {
  22182. if (this._materialEffect === effect) {
  22183. return;
  22184. }
  22185. this._materialDefines = defines;
  22186. this._materialEffect = effect;
  22187. };
  22188. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22189. get: function () {
  22190. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22191. },
  22192. enumerable: true,
  22193. configurable: true
  22194. });
  22195. /**
  22196. * Returns the submesh BoudingInfo object.
  22197. */
  22198. SubMesh.prototype.getBoundingInfo = function () {
  22199. if (this.IsGlobal) {
  22200. return this._mesh.getBoundingInfo();
  22201. }
  22202. return this._boundingInfo;
  22203. };
  22204. /**
  22205. * Sets the submesh BoundingInfo.
  22206. * Return the SubMesh.
  22207. */
  22208. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22209. this._boundingInfo = boundingInfo;
  22210. return this;
  22211. };
  22212. /**
  22213. * Returns the mesh of the current submesh.
  22214. */
  22215. SubMesh.prototype.getMesh = function () {
  22216. return this._mesh;
  22217. };
  22218. /**
  22219. * Returns the rendering mesh of the submesh.
  22220. */
  22221. SubMesh.prototype.getRenderingMesh = function () {
  22222. return this._renderingMesh;
  22223. };
  22224. /**
  22225. * Returns the submesh material.
  22226. */
  22227. SubMesh.prototype.getMaterial = function () {
  22228. var rootMaterial = this._renderingMesh.material;
  22229. if (rootMaterial && rootMaterial.getSubMaterial) {
  22230. var multiMaterial = rootMaterial;
  22231. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22232. if (this._currentMaterial !== effectiveMaterial) {
  22233. this._currentMaterial = effectiveMaterial;
  22234. if (this._materialDefines) {
  22235. this._materialDefines.markAllAsDirty();
  22236. }
  22237. }
  22238. return effectiveMaterial;
  22239. }
  22240. if (!rootMaterial) {
  22241. return this._mesh.getScene().defaultMaterial;
  22242. }
  22243. return rootMaterial;
  22244. };
  22245. // Methods
  22246. /**
  22247. * Sets a new updated BoundingInfo object to the submesh.
  22248. * Returns the SubMesh.
  22249. */
  22250. SubMesh.prototype.refreshBoundingInfo = function () {
  22251. this._lastColliderWorldVertices = null;
  22252. if (this.IsGlobal) {
  22253. return;
  22254. }
  22255. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22256. if (!data) {
  22257. this._boundingInfo = this._mesh._boundingInfo;
  22258. return;
  22259. }
  22260. var indices = this._renderingMesh.getIndices();
  22261. var extend;
  22262. //is this the only submesh?
  22263. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22264. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22265. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22266. }
  22267. else {
  22268. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22269. }
  22270. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22271. return this;
  22272. };
  22273. SubMesh.prototype._checkCollision = function (collider) {
  22274. return this.getBoundingInfo()._checkCollision(collider);
  22275. };
  22276. /**
  22277. * Updates the submesh BoundingInfo.
  22278. * Returns the Submesh.
  22279. */
  22280. SubMesh.prototype.updateBoundingInfo = function (world) {
  22281. if (!this.getBoundingInfo()) {
  22282. this.refreshBoundingInfo();
  22283. }
  22284. this.getBoundingInfo().update(world);
  22285. return this;
  22286. };
  22287. /**
  22288. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22289. * Boolean returned.
  22290. */
  22291. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22292. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22293. };
  22294. /**
  22295. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22296. * Boolean returned.
  22297. */
  22298. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22299. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22300. };
  22301. /**
  22302. * Renders the submesh.
  22303. * Returns it.
  22304. */
  22305. SubMesh.prototype.render = function (enableAlphaMode) {
  22306. this._renderingMesh.render(this, enableAlphaMode);
  22307. return this;
  22308. };
  22309. /**
  22310. * Returns a new Index Buffer.
  22311. * Type returned : WebGLBuffer.
  22312. */
  22313. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22314. if (!this._linesIndexBuffer) {
  22315. var linesIndices = [];
  22316. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22317. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22318. }
  22319. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22320. this.linesIndexCount = linesIndices.length;
  22321. }
  22322. return this._linesIndexBuffer;
  22323. };
  22324. /**
  22325. * True is the passed Ray intersects the submesh bounding box.
  22326. * Boolean returned.
  22327. */
  22328. SubMesh.prototype.canIntersects = function (ray) {
  22329. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22330. };
  22331. /**
  22332. * Returns an object IntersectionInfo.
  22333. */
  22334. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22335. var intersectInfo = null;
  22336. // LineMesh first as it's also a Mesh...
  22337. if (this._mesh instanceof BABYLON.LinesMesh) {
  22338. var lineMesh = this._mesh;
  22339. // Line test
  22340. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22341. var p0 = positions[indices[index]];
  22342. var p1 = positions[indices[index + 1]];
  22343. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22344. if (length < 0) {
  22345. continue;
  22346. }
  22347. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22348. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22349. if (fastCheck) {
  22350. break;
  22351. }
  22352. }
  22353. }
  22354. }
  22355. else {
  22356. // Triangles test
  22357. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22358. var p0 = positions[indices[index]];
  22359. var p1 = positions[indices[index + 1]];
  22360. var p2 = positions[indices[index + 2]];
  22361. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22362. if (currentIntersectInfo) {
  22363. if (currentIntersectInfo.distance < 0) {
  22364. continue;
  22365. }
  22366. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22367. intersectInfo = currentIntersectInfo;
  22368. intersectInfo.faceId = index / 3;
  22369. if (fastCheck) {
  22370. break;
  22371. }
  22372. }
  22373. }
  22374. }
  22375. }
  22376. return intersectInfo;
  22377. };
  22378. // Clone
  22379. /**
  22380. * Creates a new Submesh from the passed Mesh.
  22381. */
  22382. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22383. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22384. if (!this.IsGlobal) {
  22385. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22386. }
  22387. return result;
  22388. };
  22389. // Dispose
  22390. /**
  22391. * Disposes the Submesh.
  22392. * Returns nothing.
  22393. */
  22394. SubMesh.prototype.dispose = function () {
  22395. if (this._linesIndexBuffer) {
  22396. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22397. this._linesIndexBuffer = null;
  22398. }
  22399. // Remove from mesh
  22400. var index = this._mesh.subMeshes.indexOf(this);
  22401. this._mesh.subMeshes.splice(index, 1);
  22402. };
  22403. // Statics
  22404. /**
  22405. * Creates a new Submesh from the passed parameters :
  22406. * - materialIndex (integer) : the index of the main mesh material.
  22407. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22408. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22409. * - mesh (Mesh) : the main mesh to create the submesh from.
  22410. * - renderingMesh (optional Mesh) : rendering mesh.
  22411. */
  22412. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22413. var minVertexIndex = Number.MAX_VALUE;
  22414. var maxVertexIndex = -Number.MAX_VALUE;
  22415. renderingMesh = renderingMesh || mesh;
  22416. var indices = renderingMesh.getIndices();
  22417. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22418. var vertexIndex = indices[index];
  22419. if (vertexIndex < minVertexIndex)
  22420. minVertexIndex = vertexIndex;
  22421. if (vertexIndex > maxVertexIndex)
  22422. maxVertexIndex = vertexIndex;
  22423. }
  22424. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22425. };
  22426. return SubMesh;
  22427. }());
  22428. BABYLON.SubMesh = SubMesh;
  22429. })(BABYLON || (BABYLON = {}));
  22430. //# sourceMappingURL=babylon.subMesh.js.map
  22431. var BABYLON;
  22432. (function (BABYLON) {
  22433. var EffectFallbacks = (function () {
  22434. function EffectFallbacks() {
  22435. this._defines = {};
  22436. this._currentRank = 32;
  22437. this._maxRank = -1;
  22438. }
  22439. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22440. if (!this._defines[rank]) {
  22441. if (rank < this._currentRank) {
  22442. this._currentRank = rank;
  22443. }
  22444. if (rank > this._maxRank) {
  22445. this._maxRank = rank;
  22446. }
  22447. this._defines[rank] = new Array();
  22448. }
  22449. this._defines[rank].push(define);
  22450. };
  22451. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22452. this._meshRank = rank;
  22453. this._mesh = mesh;
  22454. if (rank < this._currentRank) {
  22455. this._currentRank = rank;
  22456. }
  22457. if (rank > this._maxRank) {
  22458. this._maxRank = rank;
  22459. }
  22460. };
  22461. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22462. get: function () {
  22463. return this._currentRank <= this._maxRank;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22469. // First we try to switch to CPU skinning
  22470. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22471. this._mesh.computeBonesUsingShaders = false;
  22472. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22473. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22474. var scene = this._mesh.getScene();
  22475. for (var index = 0; index < scene.meshes.length; index++) {
  22476. var otherMesh = scene.meshes[index];
  22477. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22478. otherMesh.computeBonesUsingShaders = false;
  22479. }
  22480. }
  22481. }
  22482. else {
  22483. var currentFallbacks = this._defines[this._currentRank];
  22484. if (currentFallbacks) {
  22485. for (var index = 0; index < currentFallbacks.length; index++) {
  22486. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22487. }
  22488. }
  22489. this._currentRank++;
  22490. }
  22491. return currentDefines;
  22492. };
  22493. return EffectFallbacks;
  22494. }());
  22495. BABYLON.EffectFallbacks = EffectFallbacks;
  22496. var EffectCreationOptions = (function () {
  22497. function EffectCreationOptions() {
  22498. }
  22499. return EffectCreationOptions;
  22500. }());
  22501. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22502. var Effect = (function () {
  22503. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22504. var _this = this;
  22505. this.uniqueId = 0;
  22506. this._uniformBuffersNames = {};
  22507. this._isReady = false;
  22508. this._compilationError = "";
  22509. this._valueCache = {};
  22510. this.name = baseName;
  22511. if (attributesNamesOrOptions.attributes) {
  22512. var options = attributesNamesOrOptions;
  22513. this._engine = uniformsNamesOrEngine;
  22514. this._attributesNames = options.attributes;
  22515. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22516. this._samplers = options.samplers;
  22517. this.defines = options.defines;
  22518. this.onError = options.onError;
  22519. this.onCompiled = options.onCompiled;
  22520. this._fallbacks = options.fallbacks;
  22521. this._indexParameters = options.indexParameters;
  22522. if (options.uniformBuffersNames) {
  22523. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22524. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22525. }
  22526. }
  22527. }
  22528. else {
  22529. this._engine = engine;
  22530. this.defines = defines;
  22531. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22532. this._samplers = samplers;
  22533. this._attributesNames = attributesNamesOrOptions;
  22534. this.onError = onError;
  22535. this.onCompiled = onCompiled;
  22536. this._indexParameters = indexParameters;
  22537. this._fallbacks = fallbacks;
  22538. }
  22539. this.uniqueId = Effect._uniqueIdSeed++;
  22540. var vertexSource;
  22541. var fragmentSource;
  22542. if (baseName.vertexElement) {
  22543. vertexSource = document.getElementById(baseName.vertexElement);
  22544. if (!vertexSource) {
  22545. vertexSource = baseName.vertexElement;
  22546. }
  22547. }
  22548. else {
  22549. vertexSource = baseName.vertex || baseName;
  22550. }
  22551. if (baseName.fragmentElement) {
  22552. fragmentSource = document.getElementById(baseName.fragmentElement);
  22553. if (!fragmentSource) {
  22554. fragmentSource = baseName.fragmentElement;
  22555. }
  22556. }
  22557. else {
  22558. fragmentSource = baseName.fragment || baseName;
  22559. }
  22560. this._loadVertexShader(vertexSource, function (vertexCode) {
  22561. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22562. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22563. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22564. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22565. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22566. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22567. });
  22568. });
  22569. });
  22570. });
  22571. });
  22572. });
  22573. }
  22574. Object.defineProperty(Effect.prototype, "key", {
  22575. get: function () {
  22576. return this._key;
  22577. },
  22578. enumerable: true,
  22579. configurable: true
  22580. });
  22581. // Properties
  22582. Effect.prototype.isReady = function () {
  22583. return this._isReady;
  22584. };
  22585. Effect.prototype.getProgram = function () {
  22586. return this._program;
  22587. };
  22588. Effect.prototype.getAttributesNames = function () {
  22589. return this._attributesNames;
  22590. };
  22591. Effect.prototype.getAttributeLocation = function (index) {
  22592. return this._attributes[index];
  22593. };
  22594. Effect.prototype.getAttributeLocationByName = function (name) {
  22595. var index = this._attributesNames.indexOf(name);
  22596. return this._attributes[index];
  22597. };
  22598. Effect.prototype.getAttributesCount = function () {
  22599. return this._attributes.length;
  22600. };
  22601. Effect.prototype.getUniformIndex = function (uniformName) {
  22602. return this._uniformsNames.indexOf(uniformName);
  22603. };
  22604. Effect.prototype.getUniform = function (uniformName) {
  22605. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22606. };
  22607. Effect.prototype.getSamplers = function () {
  22608. return this._samplers;
  22609. };
  22610. Effect.prototype.getCompilationError = function () {
  22611. return this._compilationError;
  22612. };
  22613. Effect.prototype.getVertexShaderSource = function () {
  22614. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22615. };
  22616. Effect.prototype.getFragmentShaderSource = function () {
  22617. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22618. };
  22619. // Methods
  22620. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22621. // DOM element ?
  22622. if (vertex instanceof HTMLElement) {
  22623. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22624. callback(vertexCode);
  22625. return;
  22626. }
  22627. // Base64 encoded ?
  22628. if (vertex.substr(0, 7) === "base64:") {
  22629. var vertexBinary = window.atob(vertex.substr(7));
  22630. callback(vertexBinary);
  22631. return;
  22632. }
  22633. // Is in local store ?
  22634. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22635. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22636. return;
  22637. }
  22638. var vertexShaderUrl;
  22639. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22640. vertexShaderUrl = vertex;
  22641. }
  22642. else {
  22643. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22644. }
  22645. // Vertex shader
  22646. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22647. };
  22648. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22649. // DOM element ?
  22650. if (fragment instanceof HTMLElement) {
  22651. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22652. callback(fragmentCode);
  22653. return;
  22654. }
  22655. // Base64 encoded ?
  22656. if (fragment.substr(0, 7) === "base64:") {
  22657. var fragmentBinary = window.atob(fragment.substr(7));
  22658. callback(fragmentBinary);
  22659. return;
  22660. }
  22661. // Is in local store ?
  22662. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22663. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22664. return;
  22665. }
  22666. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22667. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22668. return;
  22669. }
  22670. var fragmentShaderUrl;
  22671. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22672. fragmentShaderUrl = fragment;
  22673. }
  22674. else {
  22675. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22676. }
  22677. // Fragment shader
  22678. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22679. };
  22680. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22681. // Rebuild shaders source code
  22682. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22683. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22684. vertexCode = prefix + vertexCode;
  22685. fragmentCode = prefix + fragmentCode;
  22686. // Number lines of shaders source code
  22687. var i = 2;
  22688. var regex = /\n/gm;
  22689. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22690. i = 2;
  22691. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22692. // Dump shaders name and formatted source code
  22693. if (this.name.vertexElement) {
  22694. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22695. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22696. }
  22697. else if (this.name.vertex) {
  22698. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22699. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22700. }
  22701. else {
  22702. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22703. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22704. }
  22705. };
  22706. ;
  22707. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22708. var preparedSourceCode = this._processPrecision(sourceCode);
  22709. if (this._engine.webGLVersion == 1) {
  22710. callback(preparedSourceCode);
  22711. return;
  22712. }
  22713. // Already converted
  22714. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22715. callback(preparedSourceCode.replace("#version 300 es", ""));
  22716. return;
  22717. }
  22718. // Remove extensions
  22719. // #extension GL_OES_standard_derivatives : enable
  22720. // #extension GL_EXT_shader_texture_lod : enable
  22721. // #extension GL_EXT_frag_depth : enable
  22722. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22723. var result = preparedSourceCode.replace(regex, "");
  22724. // Migrate to GLSL v300
  22725. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22726. result = result.replace(/attribute[ \t]/g, "in ");
  22727. result = result.replace(/[ \t]attribute/g, " in");
  22728. if (isFragment) {
  22729. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22730. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22731. result = result.replace(/texture2D\(/g, "texture(");
  22732. result = result.replace(/textureCube\(/g, "texture(");
  22733. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22734. result = result.replace(/gl_FragColor/g, "glFragColor");
  22735. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22736. }
  22737. callback(result);
  22738. };
  22739. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22740. var _this = this;
  22741. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22742. var match = regex.exec(sourceCode);
  22743. var returnValue = new String(sourceCode);
  22744. while (match != null) {
  22745. var includeFile = match[1];
  22746. // Uniform declaration
  22747. if (includeFile.indexOf("__decl__") !== -1) {
  22748. includeFile = includeFile.replace(/__decl__/, "");
  22749. if (this._engine.webGLVersion != 1) {
  22750. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22751. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22752. }
  22753. includeFile = includeFile + "Declaration";
  22754. }
  22755. if (Effect.IncludesShadersStore[includeFile]) {
  22756. // Substitution
  22757. var includeContent = Effect.IncludesShadersStore[includeFile];
  22758. if (match[2]) {
  22759. var splits = match[3].split(",");
  22760. for (var index = 0; index < splits.length; index += 2) {
  22761. var source = new RegExp(splits[index], "g");
  22762. var dest = splits[index + 1];
  22763. includeContent = includeContent.replace(source, dest);
  22764. }
  22765. }
  22766. if (match[4]) {
  22767. var indexString = match[5];
  22768. if (indexString.indexOf("..") !== -1) {
  22769. var indexSplits = indexString.split("..");
  22770. var minIndex = parseInt(indexSplits[0]);
  22771. var maxIndex = parseInt(indexSplits[1]);
  22772. var sourceIncludeContent = includeContent.slice(0);
  22773. includeContent = "";
  22774. if (isNaN(maxIndex)) {
  22775. maxIndex = this._indexParameters[indexSplits[1]];
  22776. }
  22777. for (var i = minIndex; i < maxIndex; i++) {
  22778. if (this._engine.webGLVersion === 1) {
  22779. // Ubo replacement
  22780. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22781. return p1 + "{X}";
  22782. });
  22783. }
  22784. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22785. }
  22786. }
  22787. else {
  22788. if (this._engine.webGLVersion === 1) {
  22789. // Ubo replacement
  22790. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22791. return p1 + "{X}";
  22792. });
  22793. }
  22794. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22795. }
  22796. }
  22797. // Replace
  22798. returnValue = returnValue.replace(match[0], includeContent);
  22799. }
  22800. else {
  22801. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22802. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22803. Effect.IncludesShadersStore[includeFile] = fileContent;
  22804. _this._processIncludes(returnValue, callback);
  22805. });
  22806. return;
  22807. }
  22808. match = regex.exec(sourceCode);
  22809. }
  22810. callback(returnValue);
  22811. };
  22812. Effect.prototype._processPrecision = function (source) {
  22813. if (source.indexOf("precision highp float") === -1) {
  22814. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22815. source = "precision mediump float;\n" + source;
  22816. }
  22817. else {
  22818. source = "precision highp float;\n" + source;
  22819. }
  22820. }
  22821. else {
  22822. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22823. source = source.replace("precision highp float", "precision mediump float");
  22824. }
  22825. }
  22826. return source;
  22827. };
  22828. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22829. try {
  22830. var engine = this._engine;
  22831. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22832. if (engine.webGLVersion > 1) {
  22833. for (var name in this._uniformBuffersNames) {
  22834. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22835. }
  22836. }
  22837. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22838. this._attributes = engine.getAttributes(this._program, attributesNames);
  22839. var index;
  22840. for (index = 0; index < this._samplers.length; index++) {
  22841. var sampler = this.getUniform(this._samplers[index]);
  22842. if (sampler == null) {
  22843. this._samplers.splice(index, 1);
  22844. index--;
  22845. }
  22846. }
  22847. engine.bindSamplers(this);
  22848. this._compilationError = "";
  22849. this._isReady = true;
  22850. if (this.onCompiled) {
  22851. this.onCompiled(this);
  22852. }
  22853. }
  22854. catch (e) {
  22855. this._compilationError = e.message;
  22856. // Let's go through fallbacks then
  22857. BABYLON.Tools.Error("Unable to compile effect:");
  22858. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22859. return " " + uniform;
  22860. }));
  22861. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22862. return " " + attribute;
  22863. }));
  22864. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22865. BABYLON.Tools.Error("Error: " + this._compilationError);
  22866. if (fallbacks && fallbacks.isMoreFallbacks) {
  22867. BABYLON.Tools.Error("Trying next fallback.");
  22868. defines = fallbacks.reduce(defines);
  22869. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22870. }
  22871. else {
  22872. if (this.onError) {
  22873. this.onError(this, this._compilationError);
  22874. }
  22875. }
  22876. }
  22877. };
  22878. Object.defineProperty(Effect.prototype, "isSupported", {
  22879. get: function () {
  22880. return this._compilationError === "";
  22881. },
  22882. enumerable: true,
  22883. configurable: true
  22884. });
  22885. Effect.prototype._bindTexture = function (channel, texture) {
  22886. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22887. };
  22888. Effect.prototype.setTexture = function (channel, texture) {
  22889. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22890. };
  22891. Effect.prototype.setTextureArray = function (channel, textures) {
  22892. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22893. var initialPos = this._samplers.indexOf(channel);
  22894. for (var index = 1; index < textures.length; index++) {
  22895. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22896. }
  22897. }
  22898. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22899. };
  22900. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22901. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22902. };
  22903. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22904. var cache = this._valueCache[uniformName];
  22905. var flag = matrix.updateFlag;
  22906. if (cache !== undefined && cache === flag) {
  22907. return false;
  22908. }
  22909. this._valueCache[uniformName] = flag;
  22910. return true;
  22911. };
  22912. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22913. var cache = this._valueCache[uniformName];
  22914. if (!cache) {
  22915. cache = [x, y];
  22916. this._valueCache[uniformName] = cache;
  22917. return true;
  22918. }
  22919. var changed = false;
  22920. if (cache[0] !== x) {
  22921. cache[0] = x;
  22922. changed = true;
  22923. }
  22924. if (cache[1] !== y) {
  22925. cache[1] = y;
  22926. changed = true;
  22927. }
  22928. return changed;
  22929. };
  22930. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22931. var cache = this._valueCache[uniformName];
  22932. if (!cache) {
  22933. cache = [x, y, z];
  22934. this._valueCache[uniformName] = cache;
  22935. return true;
  22936. }
  22937. var changed = false;
  22938. if (cache[0] !== x) {
  22939. cache[0] = x;
  22940. changed = true;
  22941. }
  22942. if (cache[1] !== y) {
  22943. cache[1] = y;
  22944. changed = true;
  22945. }
  22946. if (cache[2] !== z) {
  22947. cache[2] = z;
  22948. changed = true;
  22949. }
  22950. return changed;
  22951. };
  22952. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22953. var cache = this._valueCache[uniformName];
  22954. if (!cache) {
  22955. cache = [x, y, z, w];
  22956. this._valueCache[uniformName] = cache;
  22957. return true;
  22958. }
  22959. var changed = false;
  22960. if (cache[0] !== x) {
  22961. cache[0] = x;
  22962. changed = true;
  22963. }
  22964. if (cache[1] !== y) {
  22965. cache[1] = y;
  22966. changed = true;
  22967. }
  22968. if (cache[2] !== z) {
  22969. cache[2] = z;
  22970. changed = true;
  22971. }
  22972. if (cache[3] !== w) {
  22973. cache[3] = w;
  22974. changed = true;
  22975. }
  22976. return changed;
  22977. };
  22978. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22979. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22980. return;
  22981. }
  22982. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22983. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22984. };
  22985. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22986. this._engine.bindUniformBlock(this._program, blockName, index);
  22987. };
  22988. Effect.prototype.setIntArray = function (uniformName, array) {
  22989. this._valueCache[uniformName] = null;
  22990. this._engine.setIntArray(this.getUniform(uniformName), array);
  22991. return this;
  22992. };
  22993. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22994. this._valueCache[uniformName] = null;
  22995. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22996. return this;
  22997. };
  22998. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22999. this._valueCache[uniformName] = null;
  23000. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23001. return this;
  23002. };
  23003. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23004. this._valueCache[uniformName] = null;
  23005. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23006. return this;
  23007. };
  23008. Effect.prototype.setFloatArray = function (uniformName, array) {
  23009. this._valueCache[uniformName] = null;
  23010. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23011. return this;
  23012. };
  23013. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23014. this._valueCache[uniformName] = null;
  23015. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23016. return this;
  23017. };
  23018. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23019. this._valueCache[uniformName] = null;
  23020. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23021. return this;
  23022. };
  23023. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23024. this._valueCache[uniformName] = null;
  23025. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23026. return this;
  23027. };
  23028. Effect.prototype.setArray = function (uniformName, array) {
  23029. this._valueCache[uniformName] = null;
  23030. this._engine.setArray(this.getUniform(uniformName), array);
  23031. return this;
  23032. };
  23033. Effect.prototype.setArray2 = function (uniformName, array) {
  23034. this._valueCache[uniformName] = null;
  23035. this._engine.setArray2(this.getUniform(uniformName), array);
  23036. return this;
  23037. };
  23038. Effect.prototype.setArray3 = function (uniformName, array) {
  23039. this._valueCache[uniformName] = null;
  23040. this._engine.setArray3(this.getUniform(uniformName), array);
  23041. return this;
  23042. };
  23043. Effect.prototype.setArray4 = function (uniformName, array) {
  23044. this._valueCache[uniformName] = null;
  23045. this._engine.setArray4(this.getUniform(uniformName), array);
  23046. return this;
  23047. };
  23048. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23049. if (!matrices) {
  23050. return;
  23051. }
  23052. this._valueCache[uniformName] = null;
  23053. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23054. return this;
  23055. };
  23056. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23057. if (this._cacheMatrix(uniformName, matrix)) {
  23058. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23059. }
  23060. return this;
  23061. };
  23062. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23063. this._valueCache[uniformName] = null;
  23064. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23065. return this;
  23066. };
  23067. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23068. this._valueCache[uniformName] = null;
  23069. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23070. return this;
  23071. };
  23072. Effect.prototype.setFloat = function (uniformName, value) {
  23073. var cache = this._valueCache[uniformName];
  23074. if (cache !== undefined && cache === value)
  23075. return this;
  23076. this._valueCache[uniformName] = value;
  23077. this._engine.setFloat(this.getUniform(uniformName), value);
  23078. return this;
  23079. };
  23080. Effect.prototype.setBool = function (uniformName, bool) {
  23081. var cache = this._valueCache[uniformName];
  23082. if (cache !== undefined && cache === bool)
  23083. return this;
  23084. this._valueCache[uniformName] = bool;
  23085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23086. return this;
  23087. };
  23088. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23089. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23090. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23091. }
  23092. return this;
  23093. };
  23094. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23095. if (this._cacheFloat2(uniformName, x, y)) {
  23096. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23097. }
  23098. return this;
  23099. };
  23100. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23101. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23102. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23103. }
  23104. return this;
  23105. };
  23106. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23107. if (this._cacheFloat3(uniformName, x, y, z)) {
  23108. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23109. }
  23110. return this;
  23111. };
  23112. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23113. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23114. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23115. }
  23116. return this;
  23117. };
  23118. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23119. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23120. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23121. }
  23122. return this;
  23123. };
  23124. Effect.prototype.setColor3 = function (uniformName, color3) {
  23125. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23126. this._engine.setColor3(this.getUniform(uniformName), color3);
  23127. }
  23128. return this;
  23129. };
  23130. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23131. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23132. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23133. }
  23134. return this;
  23135. };
  23136. Effect.prototype._recombineShader = function (node) {
  23137. if (node.define) {
  23138. if (node.condition) {
  23139. var defineIndex = this.defines.indexOf("#define " + node.define);
  23140. if (defineIndex === -1) {
  23141. return null;
  23142. }
  23143. var nextComma = this.defines.indexOf("\n", defineIndex);
  23144. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23145. var condition = defineValue + node.condition;
  23146. if (!eval(condition)) {
  23147. return null;
  23148. }
  23149. }
  23150. else if (node.ndef) {
  23151. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23152. return null;
  23153. }
  23154. }
  23155. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23156. return null;
  23157. }
  23158. }
  23159. var result = "";
  23160. for (var index = 0; index < node.children.length; index++) {
  23161. var line = node.children[index];
  23162. if (line.children) {
  23163. var combined = this._recombineShader(line);
  23164. if (combined !== null) {
  23165. result += combined + "\r\n";
  23166. }
  23167. continue;
  23168. }
  23169. if (line.length > 0) {
  23170. result += line + "\r\n";
  23171. }
  23172. }
  23173. return result;
  23174. };
  23175. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23176. var root = {
  23177. children: []
  23178. };
  23179. var currentNode = root;
  23180. var lines = shaderString.split("\n");
  23181. for (var index = 0; index < lines.length; index++) {
  23182. var line = lines[index].trim();
  23183. // #ifdef
  23184. var pos = line.indexOf("#ifdef ");
  23185. if (pos !== -1) {
  23186. var define = line.substr(pos + 7);
  23187. var newNode = {
  23188. condition: null,
  23189. ndef: false,
  23190. define: define,
  23191. children: [],
  23192. parent: currentNode
  23193. };
  23194. currentNode.children.push(newNode);
  23195. currentNode = newNode;
  23196. continue;
  23197. }
  23198. // #ifndef
  23199. var pos = line.indexOf("#ifndef ");
  23200. if (pos !== -1) {
  23201. var define = line.substr(pos + 8);
  23202. newNode = {
  23203. condition: null,
  23204. define: define,
  23205. ndef: true,
  23206. children: [],
  23207. parent: currentNode
  23208. };
  23209. currentNode.children.push(newNode);
  23210. currentNode = newNode;
  23211. continue;
  23212. }
  23213. // #if
  23214. var pos = line.indexOf("#if ");
  23215. if (pos !== -1) {
  23216. var define = line.substr(pos + 4).trim();
  23217. var conditionPos = define.indexOf(" ");
  23218. newNode = {
  23219. condition: define.substr(conditionPos + 1),
  23220. define: define.substr(0, conditionPos),
  23221. ndef: false,
  23222. children: [],
  23223. parent: currentNode
  23224. };
  23225. currentNode.children.push(newNode);
  23226. currentNode = newNode;
  23227. continue;
  23228. }
  23229. // #endif
  23230. pos = line.indexOf("#endif");
  23231. if (pos !== -1) {
  23232. currentNode = currentNode.parent;
  23233. continue;
  23234. }
  23235. currentNode.children.push(line);
  23236. }
  23237. // Recombine
  23238. return this._recombineShader(root);
  23239. };
  23240. return Effect;
  23241. }());
  23242. Effect._uniqueIdSeed = 0;
  23243. Effect._baseCache = {};
  23244. // Statics
  23245. Effect.ShadersStore = {};
  23246. Effect.IncludesShadersStore = {};
  23247. BABYLON.Effect = Effect;
  23248. })(BABYLON || (BABYLON = {}));
  23249. //# sourceMappingURL=babylon.effect.js.map
  23250. var BABYLON;
  23251. (function (BABYLON) {
  23252. var MaterialHelper = (function () {
  23253. function MaterialHelper() {
  23254. }
  23255. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23256. if (defines._areMiscDirty) {
  23257. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23258. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23259. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23260. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23261. }
  23262. };
  23263. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23264. var changed = false;
  23265. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23266. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23267. changed = true;
  23268. }
  23269. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23270. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23271. changed = true;
  23272. }
  23273. if (defines["INSTANCES"] !== useInstances) {
  23274. defines["INSTANCES"] = useInstances;
  23275. changed = true;
  23276. }
  23277. if (changed) {
  23278. defines.markAsUnprocessed();
  23279. }
  23280. };
  23281. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23282. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23283. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23284. return;
  23285. }
  23286. defines._normals = defines._needNormals;
  23287. defines._uvs = defines._needUVs;
  23288. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23289. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23290. defines["TANGENT"] = true;
  23291. }
  23292. if (defines._needUVs) {
  23293. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23294. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23295. }
  23296. else {
  23297. defines["UV1"] = false;
  23298. defines["UV2"] = false;
  23299. }
  23300. if (useVertexColor) {
  23301. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23302. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23303. }
  23304. if (useBones) {
  23305. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23306. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23307. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23308. }
  23309. else {
  23310. defines["NUM_BONE_INFLUENCERS"] = 0;
  23311. defines["BonesPerMesh"] = 0;
  23312. }
  23313. }
  23314. if (useMorphTargets) {
  23315. if (mesh.morphTargetManager) {
  23316. var manager = mesh.morphTargetManager;
  23317. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23318. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23319. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23320. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23321. }
  23322. else {
  23323. defines["MORPHTARGETS_TANGENT"] = false;
  23324. defines["MORPHTARGETS_NORMAL"] = false;
  23325. defines["MORPHTARGETS"] = false;
  23326. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23327. }
  23328. }
  23329. };
  23330. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23331. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23332. if (disableLighting === void 0) { disableLighting = false; }
  23333. if (!defines._areLightsDirty) {
  23334. return defines._needNormals;
  23335. }
  23336. var lightIndex = 0;
  23337. var needNormals = false;
  23338. var needRebuild = false;
  23339. var lightmapMode = false;
  23340. var shadowEnabled = false;
  23341. var specularEnabled = false;
  23342. if (scene.lightsEnabled && !disableLighting) {
  23343. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23344. var light = _a[_i];
  23345. needNormals = true;
  23346. if (defines["LIGHT" + lightIndex] === undefined) {
  23347. needRebuild = true;
  23348. }
  23349. defines["LIGHT" + lightIndex] = true;
  23350. defines["SPOTLIGHT" + lightIndex] = false;
  23351. defines["HEMILIGHT" + lightIndex] = false;
  23352. defines["POINTLIGHT" + lightIndex] = false;
  23353. defines["DIRLIGHT" + lightIndex] = false;
  23354. var type;
  23355. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23356. type = "SPOTLIGHT" + lightIndex;
  23357. }
  23358. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23359. type = "HEMILIGHT" + lightIndex;
  23360. }
  23361. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23362. type = "POINTLIGHT" + lightIndex;
  23363. }
  23364. else {
  23365. type = "DIRLIGHT" + lightIndex;
  23366. }
  23367. defines[type] = true;
  23368. // Specular
  23369. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23370. specularEnabled = true;
  23371. }
  23372. // Shadows
  23373. defines["SHADOW" + lightIndex] = false;
  23374. defines["SHADOWPCF" + lightIndex] = false;
  23375. defines["SHADOWESM" + lightIndex] = false;
  23376. defines["SHADOWCUBE" + lightIndex] = false;
  23377. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23378. var shadowGenerator = light.getShadowGenerator();
  23379. if (shadowGenerator) {
  23380. shadowEnabled = true;
  23381. shadowGenerator.prepareDefines(defines, lightIndex);
  23382. }
  23383. }
  23384. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23385. lightmapMode = true;
  23386. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23387. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23388. }
  23389. else {
  23390. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23391. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23392. }
  23393. lightIndex++;
  23394. if (lightIndex === maxSimultaneousLights)
  23395. break;
  23396. }
  23397. }
  23398. defines["SPECULARTERM"] = specularEnabled;
  23399. defines["SHADOWS"] = shadowEnabled;
  23400. // Resetting all other lights if any
  23401. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23402. if (defines["LIGHT" + index] !== undefined) {
  23403. defines["LIGHT" + index] = false;
  23404. }
  23405. }
  23406. var caps = scene.getEngine().getCaps();
  23407. if (defines["SHADOWFLOAT"] === undefined) {
  23408. needRebuild = true;
  23409. }
  23410. defines["SHADOWFLOAT"] = shadowEnabled &&
  23411. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23412. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23413. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23414. if (needRebuild) {
  23415. defines.rebuild();
  23416. }
  23417. return needNormals;
  23418. };
  23419. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23420. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23421. var uniformsList, uniformBuffersList, samplersList, defines;
  23422. if (uniformsListOrOptions.uniformsNames) {
  23423. var options = uniformsListOrOptions;
  23424. uniformsList = options.uniformsNames;
  23425. uniformBuffersList = options.uniformBuffersNames;
  23426. samplersList = options.samplers;
  23427. defines = options.defines;
  23428. maxSimultaneousLights = options.maxSimultaneousLights;
  23429. }
  23430. else {
  23431. uniformsList = uniformsListOrOptions;
  23432. }
  23433. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23434. if (!defines["LIGHT" + lightIndex]) {
  23435. break;
  23436. }
  23437. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23438. if (uniformBuffersList) {
  23439. uniformBuffersList.push("Light" + lightIndex);
  23440. }
  23441. samplersList.push("shadowSampler" + lightIndex);
  23442. }
  23443. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23444. uniformsList.push("morphTargetInfluences");
  23445. }
  23446. };
  23447. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23448. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23449. if (!defines["SHADOWS"]) {
  23450. return;
  23451. }
  23452. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23453. if (!defines["LIGHT" + lightIndex]) {
  23454. break;
  23455. }
  23456. if (lightIndex > 0) {
  23457. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23458. }
  23459. if (defines["SHADOW" + lightIndex]) {
  23460. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23461. }
  23462. if (defines["SHADOWPCF" + lightIndex]) {
  23463. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23464. }
  23465. if (defines["SHADOWESM" + lightIndex]) {
  23466. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23467. }
  23468. }
  23469. };
  23470. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23471. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23472. if (influencers > 0) {
  23473. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23474. var manager = mesh.morphTargetManager;
  23475. var normal = manager.supportsNormals && defines["NORMAL"];
  23476. var tangent = manager.supportsTangents && defines["TANGENT"];
  23477. for (var index = 0; index < influencers; index++) {
  23478. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23479. if (normal) {
  23480. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23481. }
  23482. if (tangent) {
  23483. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23484. }
  23485. if (attribs.length > maxAttributesCount) {
  23486. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23487. }
  23488. }
  23489. }
  23490. };
  23491. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23492. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23493. fallbacks.addCPUSkinningFallback(0, mesh);
  23494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23496. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23497. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23498. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23499. }
  23500. }
  23501. };
  23502. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23503. if (defines["INSTANCES"]) {
  23504. attribs.push("world0");
  23505. attribs.push("world1");
  23506. attribs.push("world2");
  23507. attribs.push("world3");
  23508. }
  23509. };
  23510. // Bindings
  23511. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23512. if (light.shadowEnabled && mesh.receiveShadows) {
  23513. var shadowGenerator = light.getShadowGenerator();
  23514. if (shadowGenerator) {
  23515. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23516. }
  23517. }
  23518. return depthValuesAlreadySet;
  23519. };
  23520. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23521. light.transferToEffect(effect, lightIndex + "");
  23522. };
  23523. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23524. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23525. var lightIndex = 0;
  23526. var depthValuesAlreadySet = false;
  23527. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23528. var light = _a[_i];
  23529. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23530. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23531. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23532. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23533. if (defines["SPECULARTERM"]) {
  23534. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23535. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23536. }
  23537. // Shadows
  23538. if (scene.shadowsEnabled) {
  23539. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23540. }
  23541. light._uniformBuffer.update();
  23542. lightIndex++;
  23543. if (lightIndex === maxSimultaneousLights)
  23544. break;
  23545. }
  23546. };
  23547. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23548. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23549. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23550. effect.setColor3("vFogColor", scene.fogColor);
  23551. }
  23552. };
  23553. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23554. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23555. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23556. if (matrices) {
  23557. effect.setMatrices("mBones", matrices);
  23558. }
  23559. }
  23560. };
  23561. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23562. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23563. return;
  23564. }
  23565. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23566. };
  23567. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23568. if (defines["LOGARITHMICDEPTH"]) {
  23569. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23570. }
  23571. };
  23572. MaterialHelper.BindClipPlane = function (effect, scene) {
  23573. if (scene.clipPlane) {
  23574. var clipPlane = scene.clipPlane;
  23575. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23576. }
  23577. };
  23578. return MaterialHelper;
  23579. }());
  23580. BABYLON.MaterialHelper = MaterialHelper;
  23581. })(BABYLON || (BABYLON = {}));
  23582. //# sourceMappingURL=babylon.materialHelper.js.map
  23583. var BABYLON;
  23584. (function (BABYLON) {
  23585. var MaterialDefines = (function () {
  23586. function MaterialDefines() {
  23587. this._isDirty = true;
  23588. this._areLightsDirty = true;
  23589. this._areAttributesDirty = true;
  23590. this._areTexturesDirty = true;
  23591. this._areFresnelDirty = true;
  23592. this._areMiscDirty = true;
  23593. this._normals = false;
  23594. this._uvs = false;
  23595. this._needNormals = false;
  23596. this._needUVs = false;
  23597. }
  23598. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23599. get: function () {
  23600. return this._isDirty;
  23601. },
  23602. enumerable: true,
  23603. configurable: true
  23604. });
  23605. MaterialDefines.prototype.markAsProcessed = function () {
  23606. this._isDirty = false;
  23607. this._areAttributesDirty = false;
  23608. this._areTexturesDirty = false;
  23609. this._areFresnelDirty = false;
  23610. this._areLightsDirty = false;
  23611. this._areMiscDirty = false;
  23612. };
  23613. MaterialDefines.prototype.markAsUnprocessed = function () {
  23614. this._isDirty = true;
  23615. };
  23616. MaterialDefines.prototype.markAllAsDirty = function () {
  23617. this._areTexturesDirty = true;
  23618. this._areAttributesDirty = true;
  23619. this._areLightsDirty = true;
  23620. this._areFresnelDirty = true;
  23621. this._areMiscDirty = true;
  23622. this._isDirty = true;
  23623. };
  23624. MaterialDefines.prototype.markAsLightDirty = function () {
  23625. this._areLightsDirty = true;
  23626. this._isDirty = true;
  23627. };
  23628. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23629. this._areAttributesDirty = true;
  23630. this._isDirty = true;
  23631. };
  23632. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23633. this._areTexturesDirty = true;
  23634. this._isDirty = true;
  23635. };
  23636. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23637. this._areFresnelDirty = true;
  23638. this._isDirty = true;
  23639. };
  23640. MaterialDefines.prototype.markAsMiscDirty = function () {
  23641. this._areMiscDirty = true;
  23642. this._isDirty = true;
  23643. };
  23644. MaterialDefines.prototype.rebuild = function () {
  23645. if (this._keys) {
  23646. delete this._keys;
  23647. }
  23648. this._keys = [];
  23649. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23650. var key = _a[_i];
  23651. if (key[0] === "_") {
  23652. continue;
  23653. }
  23654. this._keys.push(key);
  23655. }
  23656. };
  23657. MaterialDefines.prototype.isEqual = function (other) {
  23658. if (this._keys.length !== other._keys.length) {
  23659. return false;
  23660. }
  23661. for (var index = 0; index < this._keys.length; index++) {
  23662. var prop = this._keys[index];
  23663. if (this[prop] !== other[prop]) {
  23664. return false;
  23665. }
  23666. }
  23667. return true;
  23668. };
  23669. MaterialDefines.prototype.cloneTo = function (other) {
  23670. if (this._keys.length !== other._keys.length) {
  23671. other._keys = this._keys.slice(0);
  23672. }
  23673. for (var index = 0; index < this._keys.length; index++) {
  23674. var prop = this._keys[index];
  23675. other[prop] = this[prop];
  23676. }
  23677. };
  23678. MaterialDefines.prototype.reset = function () {
  23679. for (var index = 0; index < this._keys.length; index++) {
  23680. var prop = this._keys[index];
  23681. if (typeof (this[prop]) === "number") {
  23682. this[prop] = 0;
  23683. }
  23684. else {
  23685. this[prop] = false;
  23686. }
  23687. }
  23688. };
  23689. MaterialDefines.prototype.toString = function () {
  23690. var result = "";
  23691. for (var index = 0; index < this._keys.length; index++) {
  23692. var prop = this._keys[index];
  23693. var value = this[prop];
  23694. if (typeof (value) === "number") {
  23695. result += "#define " + prop + " " + this[prop] + "\n";
  23696. }
  23697. else if (value) {
  23698. result += "#define " + prop + "\n";
  23699. }
  23700. }
  23701. return result;
  23702. };
  23703. return MaterialDefines;
  23704. }());
  23705. BABYLON.MaterialDefines = MaterialDefines;
  23706. var Material = (function () {
  23707. function Material(name, scene, doNotAdd) {
  23708. this.checkReadyOnEveryCall = false;
  23709. this.checkReadyOnlyOnce = false;
  23710. this.state = "";
  23711. this.alpha = 1.0;
  23712. this._backFaceCulling = true;
  23713. this.doNotSerialize = false;
  23714. this.storeEffectOnSubMeshes = false;
  23715. /**
  23716. * An event triggered when the material is disposed.
  23717. * @type {BABYLON.Observable}
  23718. */
  23719. this.onDisposeObservable = new BABYLON.Observable();
  23720. /**
  23721. * An event triggered when the material is bound.
  23722. * @type {BABYLON.Observable}
  23723. */
  23724. this.onBindObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered when the material is unbound.
  23727. * @type {BABYLON.Observable}
  23728. */
  23729. this.onUnBindObservable = new BABYLON.Observable();
  23730. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23731. this.disableDepthWrite = false;
  23732. this._fogEnabled = true;
  23733. this.pointSize = 1.0;
  23734. this.zOffset = 0;
  23735. this._wasPreviouslyReady = false;
  23736. this._fillMode = Material.TriangleFillMode;
  23737. this.name = name;
  23738. this.id = name;
  23739. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23740. if (this._scene.useRightHandedSystem) {
  23741. this.sideOrientation = Material.ClockWiseSideOrientation;
  23742. }
  23743. else {
  23744. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23745. }
  23746. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23747. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23748. if (!doNotAdd) {
  23749. this._scene.materials.push(this);
  23750. }
  23751. }
  23752. Object.defineProperty(Material, "TriangleFillMode", {
  23753. get: function () {
  23754. return Material._TriangleFillMode;
  23755. },
  23756. enumerable: true,
  23757. configurable: true
  23758. });
  23759. Object.defineProperty(Material, "WireFrameFillMode", {
  23760. get: function () {
  23761. return Material._WireFrameFillMode;
  23762. },
  23763. enumerable: true,
  23764. configurable: true
  23765. });
  23766. Object.defineProperty(Material, "PointFillMode", {
  23767. get: function () {
  23768. return Material._PointFillMode;
  23769. },
  23770. enumerable: true,
  23771. configurable: true
  23772. });
  23773. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23774. get: function () {
  23775. return Material._ClockWiseSideOrientation;
  23776. },
  23777. enumerable: true,
  23778. configurable: true
  23779. });
  23780. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23781. get: function () {
  23782. return Material._CounterClockWiseSideOrientation;
  23783. },
  23784. enumerable: true,
  23785. configurable: true
  23786. });
  23787. Object.defineProperty(Material, "TextureDirtyFlag", {
  23788. get: function () {
  23789. return Material._TextureDirtyFlag;
  23790. },
  23791. enumerable: true,
  23792. configurable: true
  23793. });
  23794. Object.defineProperty(Material, "LightDirtyFlag", {
  23795. get: function () {
  23796. return Material._LightDirtyFlag;
  23797. },
  23798. enumerable: true,
  23799. configurable: true
  23800. });
  23801. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23802. get: function () {
  23803. return Material._FresnelDirtyFlag;
  23804. },
  23805. enumerable: true,
  23806. configurable: true
  23807. });
  23808. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23809. get: function () {
  23810. return Material._AttributesDirtyFlag;
  23811. },
  23812. enumerable: true,
  23813. configurable: true
  23814. });
  23815. Object.defineProperty(Material, "MiscDirtyFlag", {
  23816. get: function () {
  23817. return Material._MiscDirtyFlag;
  23818. },
  23819. enumerable: true,
  23820. configurable: true
  23821. });
  23822. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23823. get: function () {
  23824. return this._backFaceCulling;
  23825. },
  23826. set: function (value) {
  23827. if (this._backFaceCulling === value) {
  23828. return;
  23829. }
  23830. this._backFaceCulling = value;
  23831. this.markAsDirty(Material.TextureDirtyFlag);
  23832. },
  23833. enumerable: true,
  23834. configurable: true
  23835. });
  23836. Object.defineProperty(Material.prototype, "onDispose", {
  23837. set: function (callback) {
  23838. if (this._onDisposeObserver) {
  23839. this.onDisposeObservable.remove(this._onDisposeObserver);
  23840. }
  23841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23842. },
  23843. enumerable: true,
  23844. configurable: true
  23845. });
  23846. Object.defineProperty(Material.prototype, "onBind", {
  23847. set: function (callback) {
  23848. if (this._onBindObserver) {
  23849. this.onBindObservable.remove(this._onBindObserver);
  23850. }
  23851. this._onBindObserver = this.onBindObservable.add(callback);
  23852. },
  23853. enumerable: true,
  23854. configurable: true
  23855. });
  23856. Object.defineProperty(Material.prototype, "fogEnabled", {
  23857. get: function () {
  23858. return this._fogEnabled;
  23859. },
  23860. set: function (value) {
  23861. if (this._fogEnabled === value) {
  23862. return;
  23863. }
  23864. this._fogEnabled = value;
  23865. this.markAsDirty(Material.MiscDirtyFlag);
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(Material.prototype, "wireframe", {
  23871. get: function () {
  23872. return this._fillMode === Material.WireFrameFillMode;
  23873. },
  23874. set: function (value) {
  23875. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(Material.prototype, "pointsCloud", {
  23881. get: function () {
  23882. return this._fillMode === Material.PointFillMode;
  23883. },
  23884. set: function (value) {
  23885. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23886. },
  23887. enumerable: true,
  23888. configurable: true
  23889. });
  23890. Object.defineProperty(Material.prototype, "fillMode", {
  23891. get: function () {
  23892. return this._fillMode;
  23893. },
  23894. set: function (value) {
  23895. if (this._fillMode === value) {
  23896. return;
  23897. }
  23898. this._fillMode = value;
  23899. this.markAsDirty(Material.MiscDirtyFlag);
  23900. },
  23901. enumerable: true,
  23902. configurable: true
  23903. });
  23904. /**
  23905. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23906. * subclasses should override adding information pertainent to themselves
  23907. */
  23908. Material.prototype.toString = function (fullDetails) {
  23909. var ret = "Name: " + this.name;
  23910. if (fullDetails) {
  23911. }
  23912. return ret;
  23913. };
  23914. /**
  23915. * Child classes can use it to update shaders
  23916. */
  23917. Material.prototype.markAsDirty = function (flag) {
  23918. };
  23919. Material.prototype.getClassName = function () {
  23920. return "Material";
  23921. };
  23922. Object.defineProperty(Material.prototype, "isFrozen", {
  23923. get: function () {
  23924. return this.checkReadyOnlyOnce;
  23925. },
  23926. enumerable: true,
  23927. configurable: true
  23928. });
  23929. Material.prototype.freeze = function () {
  23930. this.checkReadyOnlyOnce = true;
  23931. };
  23932. Material.prototype.unfreeze = function () {
  23933. this.checkReadyOnlyOnce = false;
  23934. };
  23935. Material.prototype.isReady = function (mesh, useInstances) {
  23936. return true;
  23937. };
  23938. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23939. return false;
  23940. };
  23941. Material.prototype.getEffect = function () {
  23942. return this._effect;
  23943. };
  23944. Material.prototype.getScene = function () {
  23945. return this._scene;
  23946. };
  23947. Material.prototype.needAlphaBlending = function () {
  23948. return (this.alpha < 1.0);
  23949. };
  23950. Material.prototype.needAlphaTesting = function () {
  23951. return false;
  23952. };
  23953. Material.prototype.getAlphaTestTexture = function () {
  23954. return null;
  23955. };
  23956. Material.prototype.markDirty = function () {
  23957. this._wasPreviouslyReady = false;
  23958. };
  23959. Material.prototype._preBind = function (effect) {
  23960. var engine = this._scene.getEngine();
  23961. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23962. engine.enableEffect(effect ? effect : this._effect);
  23963. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23964. };
  23965. Material.prototype.bind = function (world, mesh) {
  23966. };
  23967. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23968. };
  23969. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23970. };
  23971. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23972. sceneUbo.bindToEffect(effect, "Scene");
  23973. };
  23974. Material.prototype.bindView = function (effect) {
  23975. if (!this._useUBO) {
  23976. effect.setMatrix("view", this.getScene().getViewMatrix());
  23977. }
  23978. else {
  23979. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23980. }
  23981. };
  23982. Material.prototype.bindViewProjection = function (effect) {
  23983. if (!this._useUBO) {
  23984. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23985. }
  23986. else {
  23987. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23988. }
  23989. };
  23990. Material.prototype._afterBind = function (mesh) {
  23991. this._scene._cachedMaterial = this;
  23992. this.onBindObservable.notifyObservers(mesh);
  23993. if (this.disableDepthWrite) {
  23994. var engine = this._scene.getEngine();
  23995. this._cachedDepthWriteState = engine.getDepthWrite();
  23996. engine.setDepthWrite(false);
  23997. }
  23998. };
  23999. Material.prototype.unbind = function () {
  24000. this.onUnBindObservable.notifyObservers(this);
  24001. if (this.disableDepthWrite) {
  24002. var engine = this._scene.getEngine();
  24003. engine.setDepthWrite(this._cachedDepthWriteState);
  24004. }
  24005. };
  24006. Material.prototype.clone = function (name) {
  24007. return null;
  24008. };
  24009. Material.prototype.getBindedMeshes = function () {
  24010. var result = new Array();
  24011. for (var index = 0; index < this._scene.meshes.length; index++) {
  24012. var mesh = this._scene.meshes[index];
  24013. if (mesh.material === this) {
  24014. result.push(mesh);
  24015. }
  24016. }
  24017. return result;
  24018. };
  24019. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24020. // Animations
  24021. this.getScene().stopAnimation(this);
  24022. // Remove from scene
  24023. var index = this._scene.materials.indexOf(this);
  24024. if (index >= 0) {
  24025. this._scene.materials.splice(index, 1);
  24026. }
  24027. // Remove from meshes
  24028. for (index = 0; index < this._scene.meshes.length; index++) {
  24029. var mesh = this._scene.meshes[index];
  24030. if (mesh.material === this) {
  24031. mesh.material = null;
  24032. if (mesh.geometry) {
  24033. var geometry = mesh.geometry;
  24034. if (this.storeEffectOnSubMeshes) {
  24035. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24036. var subMesh = _a[_i];
  24037. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24038. }
  24039. }
  24040. else {
  24041. geometry._releaseVertexArrayObject(this._effect);
  24042. }
  24043. }
  24044. }
  24045. }
  24046. this._uniformBuffer.dispose();
  24047. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24048. if (forceDisposeEffect && this._effect) {
  24049. if (this.storeEffectOnSubMeshes) {
  24050. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24051. var subMesh = _c[_b];
  24052. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24053. }
  24054. }
  24055. else {
  24056. this._scene.getEngine()._releaseEffect(this._effect);
  24057. }
  24058. this._effect = null;
  24059. }
  24060. // Callback
  24061. this.onDisposeObservable.notifyObservers(this);
  24062. this.onDisposeObservable.clear();
  24063. this.onBindObservable.clear();
  24064. this.onUnBindObservable.clear();
  24065. };
  24066. Material.prototype.serialize = function () {
  24067. return BABYLON.SerializationHelper.Serialize(this);
  24068. };
  24069. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24070. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24071. multiMaterial.id = parsedMultiMaterial.id;
  24072. if (BABYLON.Tags) {
  24073. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24074. }
  24075. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24076. var subMatId = parsedMultiMaterial.materials[matIndex];
  24077. if (subMatId) {
  24078. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24079. }
  24080. else {
  24081. multiMaterial.subMaterials.push(null);
  24082. }
  24083. }
  24084. return multiMaterial;
  24085. };
  24086. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24087. if (!parsedMaterial.customType) {
  24088. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24089. }
  24090. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24091. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24092. if (!BABYLON.LegacyPBRMaterial) {
  24093. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24094. return;
  24095. }
  24096. }
  24097. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24098. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24099. ;
  24100. };
  24101. return Material;
  24102. }());
  24103. Material._TriangleFillMode = 0;
  24104. Material._WireFrameFillMode = 1;
  24105. Material._PointFillMode = 2;
  24106. Material._ClockWiseSideOrientation = 0;
  24107. Material._CounterClockWiseSideOrientation = 1;
  24108. Material._TextureDirtyFlag = 1;
  24109. Material._LightDirtyFlag = 2;
  24110. Material._FresnelDirtyFlag = 4;
  24111. Material._AttributesDirtyFlag = 8;
  24112. Material._MiscDirtyFlag = 16;
  24113. __decorate([
  24114. BABYLON.serialize()
  24115. ], Material.prototype, "id", void 0);
  24116. __decorate([
  24117. BABYLON.serialize()
  24118. ], Material.prototype, "name", void 0);
  24119. __decorate([
  24120. BABYLON.serialize()
  24121. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24122. __decorate([
  24123. BABYLON.serialize()
  24124. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24125. __decorate([
  24126. BABYLON.serialize()
  24127. ], Material.prototype, "state", void 0);
  24128. __decorate([
  24129. BABYLON.serialize()
  24130. ], Material.prototype, "alpha", void 0);
  24131. __decorate([
  24132. BABYLON.serialize("backFaceCulling")
  24133. ], Material.prototype, "_backFaceCulling", void 0);
  24134. __decorate([
  24135. BABYLON.serialize()
  24136. ], Material.prototype, "sideOrientation", void 0);
  24137. __decorate([
  24138. BABYLON.serialize()
  24139. ], Material.prototype, "alphaMode", void 0);
  24140. __decorate([
  24141. BABYLON.serialize()
  24142. ], Material.prototype, "disableDepthWrite", void 0);
  24143. __decorate([
  24144. BABYLON.serialize("fogEnabled")
  24145. ], Material.prototype, "_fogEnabled", void 0);
  24146. __decorate([
  24147. BABYLON.serialize()
  24148. ], Material.prototype, "pointSize", void 0);
  24149. __decorate([
  24150. BABYLON.serialize()
  24151. ], Material.prototype, "zOffset", void 0);
  24152. __decorate([
  24153. BABYLON.serialize()
  24154. ], Material.prototype, "wireframe", null);
  24155. __decorate([
  24156. BABYLON.serialize()
  24157. ], Material.prototype, "pointsCloud", null);
  24158. __decorate([
  24159. BABYLON.serialize()
  24160. ], Material.prototype, "fillMode", null);
  24161. BABYLON.Material = Material;
  24162. })(BABYLON || (BABYLON = {}));
  24163. //# sourceMappingURL=babylon.material.js.map
  24164. var BABYLON;
  24165. (function (BABYLON) {
  24166. var UniformBuffer = (function () {
  24167. /**
  24168. * Uniform buffer objects.
  24169. *
  24170. * Handles blocks of uniform on the GPU.
  24171. *
  24172. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24173. *
  24174. * For more information, please refer to :
  24175. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24176. */
  24177. function UniformBuffer(engine, data, dynamic) {
  24178. this._engine = engine;
  24179. this._noUBO = engine.webGLVersion === 1;
  24180. this._dynamic = dynamic;
  24181. this._data = data || [];
  24182. this._uniformLocations = {};
  24183. this._uniformSizes = {};
  24184. this._uniformLocationPointer = 0;
  24185. this._needSync = false;
  24186. if (this._noUBO) {
  24187. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24188. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24189. this.updateFloat = this._updateFloatForEffect;
  24190. this.updateFloat2 = this._updateFloat2ForEffect;
  24191. this.updateFloat3 = this._updateFloat3ForEffect;
  24192. this.updateFloat4 = this._updateFloat4ForEffect;
  24193. this.updateMatrix = this._updateMatrixForEffect;
  24194. this.updateVector3 = this._updateVector3ForEffect;
  24195. this.updateVector4 = this._updateVector4ForEffect;
  24196. this.updateColor3 = this._updateColor3ForEffect;
  24197. this.updateColor4 = this._updateColor4ForEffect;
  24198. }
  24199. else {
  24200. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24201. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24202. this.updateFloat = this._updateFloatForUniform;
  24203. this.updateFloat2 = this._updateFloat2ForUniform;
  24204. this.updateFloat3 = this._updateFloat3ForUniform;
  24205. this.updateFloat4 = this._updateFloat4ForUniform;
  24206. this.updateMatrix = this._updateMatrixForUniform;
  24207. this.updateVector3 = this._updateVector3ForUniform;
  24208. this.updateVector4 = this._updateVector4ForUniform;
  24209. this.updateColor3 = this._updateColor3ForUniform;
  24210. this.updateColor4 = this._updateColor4ForUniform;
  24211. }
  24212. }
  24213. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24214. // Properties
  24215. /**
  24216. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24217. * or just falling back on setUniformXXX calls.
  24218. */
  24219. get: function () {
  24220. return !this._noUBO;
  24221. },
  24222. enumerable: true,
  24223. configurable: true
  24224. });
  24225. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24226. /**
  24227. * Indicates if the WebGL underlying uniform buffer is in sync
  24228. * with the javascript cache data.
  24229. */
  24230. get: function () {
  24231. return !this._needSync;
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. /**
  24237. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24238. * Also, a dynamic UniformBuffer will disable cache verification and always
  24239. * update the underlying WebGL uniform buffer to the GPU.
  24240. */
  24241. UniformBuffer.prototype.isDynamic = function () {
  24242. return this._dynamic;
  24243. };
  24244. /**
  24245. * The data cache on JS side.
  24246. */
  24247. UniformBuffer.prototype.getData = function () {
  24248. return this._bufferData;
  24249. };
  24250. /**
  24251. * The underlying WebGL Uniform buffer.
  24252. */
  24253. UniformBuffer.prototype.getBuffer = function () {
  24254. return this._buffer;
  24255. };
  24256. /**
  24257. * std140 layout specifies how to align data within an UBO structure.
  24258. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24259. * for specs.
  24260. */
  24261. UniformBuffer.prototype._fillAlignment = function (size) {
  24262. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24263. // and 4x4 matrices
  24264. // TODO : change if other types are used
  24265. var alignment;
  24266. if (size <= 2) {
  24267. alignment = size;
  24268. }
  24269. else {
  24270. alignment = 4;
  24271. }
  24272. if ((this._uniformLocationPointer % alignment) !== 0) {
  24273. var oldPointer = this._uniformLocationPointer;
  24274. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24275. var diff = this._uniformLocationPointer - oldPointer;
  24276. for (var i = 0; i < diff; i++) {
  24277. this._data.push(0);
  24278. }
  24279. }
  24280. };
  24281. /**
  24282. * Adds an uniform in the buffer.
  24283. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24284. * for the layout to be correct !
  24285. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24286. * @param {number|number[]} size Data size, or data directly.
  24287. */
  24288. UniformBuffer.prototype.addUniform = function (name, size) {
  24289. if (this._noUBO) {
  24290. return;
  24291. }
  24292. if (this._uniformLocations[name] !== undefined) {
  24293. // Already existing uniform
  24294. return;
  24295. }
  24296. // This function must be called in the order of the shader layout !
  24297. // size can be the size of the uniform, or data directly
  24298. var data;
  24299. if (size instanceof Array) {
  24300. data = size;
  24301. size = data.length;
  24302. }
  24303. else {
  24304. size = size;
  24305. data = [];
  24306. // Fill with zeros
  24307. for (var i = 0; i < size; i++) {
  24308. data.push(0);
  24309. }
  24310. }
  24311. this._fillAlignment(size);
  24312. this._uniformSizes[name] = size;
  24313. this._uniformLocations[name] = this._uniformLocationPointer;
  24314. this._uniformLocationPointer += size;
  24315. for (var i = 0; i < size; i++) {
  24316. this._data.push(data[i]);
  24317. }
  24318. this._needSync = true;
  24319. };
  24320. /**
  24321. * Wrapper for addUniform.
  24322. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24323. * @param {Matrix} mat A 4x4 matrix.
  24324. */
  24325. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24326. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24327. };
  24328. /**
  24329. * Wrapper for addUniform.
  24330. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24331. * @param {number} x
  24332. * @param {number} y
  24333. */
  24334. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24335. var temp = [x, y];
  24336. this.addUniform(name, temp);
  24337. };
  24338. /**
  24339. * Wrapper for addUniform.
  24340. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24341. * @param {number} x
  24342. * @param {number} y
  24343. * @param {number} z
  24344. */
  24345. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24346. var temp = [x, y, z];
  24347. this.addUniform(name, temp);
  24348. };
  24349. /**
  24350. * Wrapper for addUniform.
  24351. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24352. * @param {Color3} color
  24353. */
  24354. UniformBuffer.prototype.addColor3 = function (name, color) {
  24355. var temp = [];
  24356. color.toArray(temp);
  24357. this.addUniform(name, temp);
  24358. };
  24359. /**
  24360. * Wrapper for addUniform.
  24361. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24362. * @param {Color3} color
  24363. * @param {number} alpha
  24364. */
  24365. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24366. var temp = [];
  24367. color.toArray(temp);
  24368. temp.push(alpha);
  24369. this.addUniform(name, temp);
  24370. };
  24371. /**
  24372. * Wrapper for addUniform.
  24373. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24374. * @param {Vector3} vector
  24375. */
  24376. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24377. var temp = [];
  24378. vector.toArray(temp);
  24379. this.addUniform(name, temp);
  24380. };
  24381. /**
  24382. * Wrapper for addUniform.
  24383. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24384. */
  24385. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24386. this.addUniform(name, 12);
  24387. };
  24388. /**
  24389. * Wrapper for addUniform.
  24390. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24391. */
  24392. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24393. this.addUniform(name, 8);
  24394. };
  24395. /**
  24396. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24397. */
  24398. UniformBuffer.prototype.create = function () {
  24399. if (this._noUBO) {
  24400. return;
  24401. }
  24402. if (this._buffer) {
  24403. return; // nothing to do
  24404. }
  24405. // See spec, alignment must be filled as a vec4
  24406. this._fillAlignment(4);
  24407. this._bufferData = new Float32Array(this._data);
  24408. if (this._dynamic) {
  24409. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24410. }
  24411. else {
  24412. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24413. }
  24414. this._needSync = true;
  24415. };
  24416. /**
  24417. * Updates the WebGL Uniform Buffer on the GPU.
  24418. * If the `dynamic` flag is set to true, no cache comparison is done.
  24419. * Otherwise, the buffer will be updated only if the cache differs.
  24420. */
  24421. UniformBuffer.prototype.update = function () {
  24422. if (!this._buffer) {
  24423. this.create();
  24424. return;
  24425. }
  24426. if (!this._dynamic && !this._needSync) {
  24427. return;
  24428. }
  24429. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24430. this._needSync = false;
  24431. };
  24432. /**
  24433. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24434. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24435. * @param {number[]|Float32Array} data Flattened data
  24436. * @param {number} size Size of the data.
  24437. */
  24438. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24439. var location = this._uniformLocations[uniformName];
  24440. if (location === undefined) {
  24441. if (this._buffer) {
  24442. // Cannot add an uniform if the buffer is already created
  24443. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24444. return;
  24445. }
  24446. this.addUniform(uniformName, size);
  24447. location = this._uniformLocations[uniformName];
  24448. }
  24449. if (!this._buffer) {
  24450. this.create();
  24451. }
  24452. if (!this._dynamic) {
  24453. // Cache for static uniform buffers
  24454. var changed = false;
  24455. for (var i = 0; i < size; i++) {
  24456. if (this._bufferData[location + i] !== data[i]) {
  24457. changed = true;
  24458. this._bufferData[location + i] = data[i];
  24459. }
  24460. }
  24461. this._needSync = this._needSync || changed;
  24462. }
  24463. else {
  24464. // No cache for dynamic
  24465. for (var i = 0; i < size; i++) {
  24466. this._bufferData[location + i] = data[i];
  24467. }
  24468. }
  24469. };
  24470. // Update methods
  24471. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24472. // To match std140, matrix must be realigned
  24473. for (var i = 0; i < 3; i++) {
  24474. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24475. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24476. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24477. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24478. }
  24479. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24480. };
  24481. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24482. this._currentEffect.setMatrix3x3(name, matrix);
  24483. };
  24484. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24485. this._currentEffect.setMatrix2x2(name, matrix);
  24486. };
  24487. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24488. // To match std140, matrix must be realigned
  24489. for (var i = 0; i < 2; i++) {
  24490. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24491. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24492. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24493. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24494. }
  24495. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24496. };
  24497. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24498. this._currentEffect.setFloat(name, x);
  24499. };
  24500. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24501. UniformBuffer._tempBuffer[0] = x;
  24502. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24503. };
  24504. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24505. this._currentEffect.setFloat2(name, x, y);
  24506. };
  24507. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24508. UniformBuffer._tempBuffer[0] = x;
  24509. UniformBuffer._tempBuffer[1] = y;
  24510. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24511. };
  24512. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24513. if (suffix === void 0) { suffix = ""; }
  24514. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24515. };
  24516. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24517. if (suffix === void 0) { suffix = ""; }
  24518. UniformBuffer._tempBuffer[0] = x;
  24519. UniformBuffer._tempBuffer[1] = y;
  24520. UniformBuffer._tempBuffer[2] = z;
  24521. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24522. };
  24523. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24524. if (suffix === void 0) { suffix = ""; }
  24525. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24526. };
  24527. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24528. if (suffix === void 0) { suffix = ""; }
  24529. UniformBuffer._tempBuffer[0] = x;
  24530. UniformBuffer._tempBuffer[1] = y;
  24531. UniformBuffer._tempBuffer[2] = z;
  24532. UniformBuffer._tempBuffer[3] = w;
  24533. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24534. };
  24535. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24536. this._currentEffect.setMatrix(name, mat);
  24537. };
  24538. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24539. this.updateUniform(name, mat.toArray(), 16);
  24540. };
  24541. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24542. this._currentEffect.setVector3(name, vector);
  24543. };
  24544. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24545. vector.toArray(UniformBuffer._tempBuffer);
  24546. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24547. };
  24548. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24549. this._currentEffect.setVector4(name, vector);
  24550. };
  24551. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24552. vector.toArray(UniformBuffer._tempBuffer);
  24553. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24554. };
  24555. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24556. if (suffix === void 0) { suffix = ""; }
  24557. this._currentEffect.setColor3(name + suffix, color);
  24558. };
  24559. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24560. if (suffix === void 0) { suffix = ""; }
  24561. color.toArray(UniformBuffer._tempBuffer);
  24562. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24563. };
  24564. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24565. if (suffix === void 0) { suffix = ""; }
  24566. this._currentEffect.setColor4(name + suffix, color, alpha);
  24567. };
  24568. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24569. if (suffix === void 0) { suffix = ""; }
  24570. color.toArray(UniformBuffer._tempBuffer);
  24571. UniformBuffer._tempBuffer[3] = alpha;
  24572. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24573. };
  24574. /**
  24575. * Sets a sampler uniform on the effect.
  24576. * @param {string} name Name of the sampler.
  24577. * @param {Texture} texture
  24578. */
  24579. UniformBuffer.prototype.setTexture = function (name, texture) {
  24580. this._currentEffect.setTexture(name, texture);
  24581. };
  24582. /**
  24583. * Directly updates the value of the uniform in the cache AND on the GPU.
  24584. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24585. * @param {number[]|Float32Array} data Flattened data
  24586. */
  24587. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24588. this.updateUniform(uniformName, data, data.length);
  24589. this.update();
  24590. };
  24591. /**
  24592. * Binds this uniform buffer to an effect.
  24593. * @param {Effect} effect
  24594. * @param {string} name Name of the uniform block in the shader.
  24595. */
  24596. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24597. this._currentEffect = effect;
  24598. if (this._noUBO) {
  24599. return;
  24600. }
  24601. effect.bindUniformBuffer(this._buffer, name);
  24602. };
  24603. /**
  24604. * Disposes the uniform buffer.
  24605. */
  24606. UniformBuffer.prototype.dispose = function () {
  24607. if (!this._buffer) {
  24608. return;
  24609. }
  24610. if (this._engine._releaseBuffer(this._buffer)) {
  24611. this._buffer = null;
  24612. }
  24613. };
  24614. return UniformBuffer;
  24615. }());
  24616. // Pool for avoiding memory leaks
  24617. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24618. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24619. BABYLON.UniformBuffer = UniformBuffer;
  24620. })(BABYLON || (BABYLON = {}));
  24621. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24622. var BABYLON;
  24623. (function (BABYLON) {
  24624. var PushMaterial = (function (_super) {
  24625. __extends(PushMaterial, _super);
  24626. function PushMaterial(name, scene) {
  24627. var _this = _super.call(this, name, scene) || this;
  24628. _this.storeEffectOnSubMeshes = true;
  24629. return _this;
  24630. }
  24631. PushMaterial.prototype.getEffect = function () {
  24632. return this._activeEffect;
  24633. };
  24634. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24635. if (!mesh) {
  24636. return false;
  24637. }
  24638. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24639. return true;
  24640. }
  24641. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24642. };
  24643. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24644. this._activeEffect.setMatrix("world", world);
  24645. };
  24646. PushMaterial.prototype.bind = function (world, mesh) {
  24647. if (!mesh) {
  24648. return;
  24649. }
  24650. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24651. };
  24652. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24653. _super.prototype._afterBind.call(this, mesh);
  24654. this.getScene()._cachedEffect = effect;
  24655. };
  24656. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24657. if (visibility === void 0) { visibility = 0; }
  24658. return scene.isCachedMaterialValid(this, effect, visibility);
  24659. };
  24660. PushMaterial.prototype.markAsDirty = function (flag) {
  24661. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24662. this._markAllSubMeshesAsTexturesDirty();
  24663. }
  24664. if (flag & BABYLON.Material.LightDirtyFlag) {
  24665. this._markAllSubMeshesAsLightsDirty();
  24666. }
  24667. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24668. this._markAllSubMeshesAsFresnelDirty();
  24669. }
  24670. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24671. this._markAllSubMeshesAsAttributesDirty();
  24672. }
  24673. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24674. this._markAllSubMeshesAsMiscDirty();
  24675. }
  24676. this.getScene().resetCachedMaterial();
  24677. };
  24678. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24679. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24680. var mesh = _a[_i];
  24681. if (!mesh.subMeshes) {
  24682. continue;
  24683. }
  24684. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24685. var subMesh = _c[_b];
  24686. if (subMesh.getMaterial() !== this) {
  24687. continue;
  24688. }
  24689. if (!subMesh._materialDefines) {
  24690. return;
  24691. }
  24692. func(subMesh._materialDefines);
  24693. }
  24694. }
  24695. };
  24696. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24697. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24698. };
  24699. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24700. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24701. };
  24702. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24703. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24704. };
  24705. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24706. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24707. };
  24708. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24709. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24710. };
  24711. return PushMaterial;
  24712. }(BABYLON.Material));
  24713. BABYLON.PushMaterial = PushMaterial;
  24714. })(BABYLON || (BABYLON = {}));
  24715. //# sourceMappingURL=babylon.pushMaterial.js.map
  24716. var BABYLON;
  24717. (function (BABYLON) {
  24718. var VertexData = (function () {
  24719. function VertexData() {
  24720. }
  24721. VertexData.prototype.set = function (data, kind) {
  24722. switch (kind) {
  24723. case BABYLON.VertexBuffer.PositionKind:
  24724. this.positions = data;
  24725. break;
  24726. case BABYLON.VertexBuffer.NormalKind:
  24727. this.normals = data;
  24728. break;
  24729. case BABYLON.VertexBuffer.TangentKind:
  24730. this.tangents = data;
  24731. break;
  24732. case BABYLON.VertexBuffer.UVKind:
  24733. this.uvs = data;
  24734. break;
  24735. case BABYLON.VertexBuffer.UV2Kind:
  24736. this.uvs2 = data;
  24737. break;
  24738. case BABYLON.VertexBuffer.UV3Kind:
  24739. this.uvs3 = data;
  24740. break;
  24741. case BABYLON.VertexBuffer.UV4Kind:
  24742. this.uvs4 = data;
  24743. break;
  24744. case BABYLON.VertexBuffer.UV5Kind:
  24745. this.uvs5 = data;
  24746. break;
  24747. case BABYLON.VertexBuffer.UV6Kind:
  24748. this.uvs6 = data;
  24749. break;
  24750. case BABYLON.VertexBuffer.ColorKind:
  24751. this.colors = data;
  24752. break;
  24753. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24754. this.matricesIndices = data;
  24755. break;
  24756. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24757. this.matricesWeights = data;
  24758. break;
  24759. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24760. this.matricesIndicesExtra = data;
  24761. break;
  24762. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24763. this.matricesWeightsExtra = data;
  24764. break;
  24765. }
  24766. };
  24767. /**
  24768. * Associates the vertexData to the passed Mesh.
  24769. * Sets it as updatable or not (default `false`).
  24770. * Returns the VertexData.
  24771. */
  24772. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24773. this._applyTo(mesh, updatable);
  24774. return this;
  24775. };
  24776. /**
  24777. * Associates the vertexData to the passed Geometry.
  24778. * Sets it as updatable or not (default `false`).
  24779. * Returns the VertexData.
  24780. */
  24781. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24782. this._applyTo(geometry, updatable);
  24783. return this;
  24784. };
  24785. /**
  24786. * Updates the associated mesh.
  24787. * Returns the VertexData.
  24788. */
  24789. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24790. this._update(mesh);
  24791. return this;
  24792. };
  24793. /**
  24794. * Updates the associated geometry.
  24795. * Returns the VertexData.
  24796. */
  24797. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24798. this._update(geometry);
  24799. return this;
  24800. };
  24801. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24802. if (this.positions) {
  24803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24804. }
  24805. if (this.normals) {
  24806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24807. }
  24808. if (this.tangents) {
  24809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24810. }
  24811. if (this.uvs) {
  24812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24813. }
  24814. if (this.uvs2) {
  24815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24816. }
  24817. if (this.uvs3) {
  24818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24819. }
  24820. if (this.uvs4) {
  24821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24822. }
  24823. if (this.uvs5) {
  24824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24825. }
  24826. if (this.uvs6) {
  24827. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24828. }
  24829. if (this.colors) {
  24830. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24831. }
  24832. if (this.matricesIndices) {
  24833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24834. }
  24835. if (this.matricesWeights) {
  24836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24837. }
  24838. if (this.matricesIndicesExtra) {
  24839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24840. }
  24841. if (this.matricesWeightsExtra) {
  24842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24843. }
  24844. if (this.indices) {
  24845. meshOrGeometry.setIndices(this.indices);
  24846. }
  24847. return this;
  24848. };
  24849. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24850. if (this.positions) {
  24851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24852. }
  24853. if (this.normals) {
  24854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24855. }
  24856. if (this.tangents) {
  24857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24858. }
  24859. if (this.uvs) {
  24860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24861. }
  24862. if (this.uvs2) {
  24863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24864. }
  24865. if (this.uvs3) {
  24866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24867. }
  24868. if (this.uvs4) {
  24869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24870. }
  24871. if (this.uvs5) {
  24872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24873. }
  24874. if (this.uvs6) {
  24875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24876. }
  24877. if (this.colors) {
  24878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24879. }
  24880. if (this.matricesIndices) {
  24881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24882. }
  24883. if (this.matricesWeights) {
  24884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24885. }
  24886. if (this.matricesIndicesExtra) {
  24887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24888. }
  24889. if (this.matricesWeightsExtra) {
  24890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24891. }
  24892. if (this.indices) {
  24893. meshOrGeometry.setIndices(this.indices);
  24894. }
  24895. return this;
  24896. };
  24897. /**
  24898. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24899. * Returns the VertexData.
  24900. */
  24901. VertexData.prototype.transform = function (matrix) {
  24902. var transformed = BABYLON.Vector3.Zero();
  24903. var index;
  24904. if (this.positions) {
  24905. var position = BABYLON.Vector3.Zero();
  24906. for (index = 0; index < this.positions.length; index += 3) {
  24907. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24908. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24909. this.positions[index] = transformed.x;
  24910. this.positions[index + 1] = transformed.y;
  24911. this.positions[index + 2] = transformed.z;
  24912. }
  24913. }
  24914. if (this.normals) {
  24915. var normal = BABYLON.Vector3.Zero();
  24916. for (index = 0; index < this.normals.length; index += 3) {
  24917. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24918. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24919. this.normals[index] = transformed.x;
  24920. this.normals[index + 1] = transformed.y;
  24921. this.normals[index + 2] = transformed.z;
  24922. }
  24923. }
  24924. if (this.tangents) {
  24925. var tangent = BABYLON.Vector4.Zero();
  24926. var tangentTransformed = BABYLON.Vector4.Zero();
  24927. for (index = 0; index < this.tangents.length; index += 4) {
  24928. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24929. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24930. this.tangents[index] = tangentTransformed.x;
  24931. this.tangents[index + 1] = tangentTransformed.y;
  24932. this.tangents[index + 2] = tangentTransformed.z;
  24933. this.tangents[index + 3] = tangentTransformed.w;
  24934. }
  24935. }
  24936. return this;
  24937. };
  24938. /**
  24939. * Merges the passed VertexData into the current one.
  24940. * Returns the modified VertexData.
  24941. */
  24942. VertexData.prototype.merge = function (other) {
  24943. if (other.indices) {
  24944. if (!this.indices) {
  24945. this.indices = [];
  24946. }
  24947. var offset = this.positions ? this.positions.length / 3 : 0;
  24948. for (var index = 0; index < other.indices.length; index++) {
  24949. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24950. this.indices.push(other.indices[index] + offset);
  24951. }
  24952. }
  24953. this.positions = this._mergeElement(this.positions, other.positions);
  24954. this.normals = this._mergeElement(this.normals, other.normals);
  24955. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24956. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24957. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24958. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24959. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24960. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24961. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24962. this.colors = this._mergeElement(this.colors, other.colors);
  24963. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24964. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24965. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24966. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24967. return this;
  24968. };
  24969. VertexData.prototype._mergeElement = function (source, other) {
  24970. if (!other)
  24971. return source;
  24972. if (!source)
  24973. return other;
  24974. var len = other.length + source.length;
  24975. var isSrcTypedArray = source instanceof Float32Array;
  24976. var isOthTypedArray = other instanceof Float32Array;
  24977. // use non-loop method when the source is Float32Array
  24978. if (isSrcTypedArray) {
  24979. var ret32 = new Float32Array(len);
  24980. ret32.set(source);
  24981. ret32.set(other, source.length);
  24982. return ret32;
  24983. // source is number[], when other is also use concat
  24984. }
  24985. else if (!isOthTypedArray) {
  24986. return source.concat(other);
  24987. // source is a number[], but other is a Float32Array, loop required
  24988. }
  24989. else {
  24990. var ret = source.slice(0); // copy source to a separate array
  24991. for (var i = 0, len = other.length; i < len; i++) {
  24992. ret.push(other[i]);
  24993. }
  24994. return ret;
  24995. }
  24996. };
  24997. /**
  24998. * Serializes the VertexData.
  24999. * Returns a serialized object.
  25000. */
  25001. VertexData.prototype.serialize = function () {
  25002. var serializationObject = this.serialize();
  25003. if (this.positions) {
  25004. serializationObject.positions = this.positions;
  25005. }
  25006. if (this.normals) {
  25007. serializationObject.normals = this.normals;
  25008. }
  25009. if (this.tangents) {
  25010. serializationObject.tangents = this.tangents;
  25011. }
  25012. if (this.uvs) {
  25013. serializationObject.uvs = this.uvs;
  25014. }
  25015. if (this.uvs2) {
  25016. serializationObject.uvs2 = this.uvs2;
  25017. }
  25018. if (this.uvs3) {
  25019. serializationObject.uvs3 = this.uvs3;
  25020. }
  25021. if (this.uvs4) {
  25022. serializationObject.uvs4 = this.uvs4;
  25023. }
  25024. if (this.uvs5) {
  25025. serializationObject.uvs5 = this.uvs5;
  25026. }
  25027. if (this.uvs6) {
  25028. serializationObject.uvs6 = this.uvs6;
  25029. }
  25030. if (this.colors) {
  25031. serializationObject.colors = this.colors;
  25032. }
  25033. if (this.matricesIndices) {
  25034. serializationObject.matricesIndices = this.matricesIndices;
  25035. serializationObject.matricesIndices._isExpanded = true;
  25036. }
  25037. if (this.matricesWeights) {
  25038. serializationObject.matricesWeights = this.matricesWeights;
  25039. }
  25040. if (this.matricesIndicesExtra) {
  25041. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25042. serializationObject.matricesIndicesExtra._isExpanded = true;
  25043. }
  25044. if (this.matricesWeightsExtra) {
  25045. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25046. }
  25047. serializationObject.indices = this.indices;
  25048. return serializationObject;
  25049. };
  25050. // Statics
  25051. /**
  25052. * Returns the object VertexData associated to the passed mesh.
  25053. */
  25054. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25055. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25056. };
  25057. /**
  25058. * Returns the object VertexData associated to the passed geometry.
  25059. */
  25060. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25061. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25062. };
  25063. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25064. var result = new VertexData();
  25065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25066. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25067. }
  25068. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25069. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25070. }
  25071. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25072. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25073. }
  25074. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25075. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25076. }
  25077. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25078. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25079. }
  25080. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25081. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25082. }
  25083. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25084. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25085. }
  25086. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25087. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25088. }
  25089. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25090. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25091. }
  25092. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25093. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25094. }
  25095. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25096. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25097. }
  25098. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25099. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25100. }
  25101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25102. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25103. }
  25104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25105. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25106. }
  25107. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25108. return result;
  25109. };
  25110. /**
  25111. * Creates the vertexData of the Ribbon.
  25112. */
  25113. VertexData.CreateRibbon = function (options) {
  25114. var pathArray = options.pathArray;
  25115. var closeArray = options.closeArray || false;
  25116. var closePath = options.closePath || false;
  25117. var invertUV = options.invertUV || false;
  25118. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25119. var offset = options.offset || defaultOffset;
  25120. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25121. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25122. var customUV = options.uvs;
  25123. var customColors = options.colors;
  25124. var positions = [];
  25125. var indices = [];
  25126. var normals = [];
  25127. var uvs = [];
  25128. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25129. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25130. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25131. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25132. var minlg; // minimal length among all paths from pathArray
  25133. var lg = []; // array of path lengths : nb of vertex per path
  25134. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25135. var p; // path iterator
  25136. var i; // point iterator
  25137. var j; // point iterator
  25138. // if single path in pathArray
  25139. if (pathArray.length < 2) {
  25140. var ar1 = [];
  25141. var ar2 = [];
  25142. for (i = 0; i < pathArray[0].length - offset; i++) {
  25143. ar1.push(pathArray[0][i]);
  25144. ar2.push(pathArray[0][i + offset]);
  25145. }
  25146. pathArray = [ar1, ar2];
  25147. }
  25148. // positions and horizontal distances (u)
  25149. var idc = 0;
  25150. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25151. var path;
  25152. var l;
  25153. minlg = pathArray[0].length;
  25154. var vectlg;
  25155. var dist;
  25156. for (p = 0; p < pathArray.length; p++) {
  25157. uTotalDistance[p] = 0;
  25158. us[p] = [0];
  25159. path = pathArray[p];
  25160. l = path.length;
  25161. minlg = (minlg < l) ? minlg : l;
  25162. j = 0;
  25163. while (j < l) {
  25164. positions.push(path[j].x, path[j].y, path[j].z);
  25165. if (j > 0) {
  25166. vectlg = path[j].subtract(path[j - 1]).length();
  25167. dist = vectlg + uTotalDistance[p];
  25168. us[p].push(dist);
  25169. uTotalDistance[p] = dist;
  25170. }
  25171. j++;
  25172. }
  25173. if (closePath) {
  25174. j--;
  25175. positions.push(path[0].x, path[0].y, path[0].z);
  25176. vectlg = path[j].subtract(path[0]).length();
  25177. dist = vectlg + uTotalDistance[p];
  25178. us[p].push(dist);
  25179. uTotalDistance[p] = dist;
  25180. }
  25181. lg[p] = l + closePathCorr;
  25182. idx[p] = idc;
  25183. idc += (l + closePathCorr);
  25184. }
  25185. // vertical distances (v)
  25186. var path1;
  25187. var path2;
  25188. var vertex1;
  25189. var vertex2;
  25190. for (i = 0; i < minlg + closePathCorr; i++) {
  25191. vTotalDistance[i] = 0;
  25192. vs[i] = [0];
  25193. for (p = 0; p < pathArray.length - 1; p++) {
  25194. path1 = pathArray[p];
  25195. path2 = pathArray[p + 1];
  25196. if (i === minlg) {
  25197. vertex1 = path1[0];
  25198. vertex2 = path2[0];
  25199. }
  25200. else {
  25201. vertex1 = path1[i];
  25202. vertex2 = path2[i];
  25203. }
  25204. vectlg = vertex2.subtract(vertex1).length();
  25205. dist = vectlg + vTotalDistance[i];
  25206. vs[i].push(dist);
  25207. vTotalDistance[i] = dist;
  25208. }
  25209. if (closeArray) {
  25210. path1 = pathArray[p];
  25211. path2 = pathArray[0];
  25212. if (i === minlg) {
  25213. vertex2 = path2[0];
  25214. }
  25215. vectlg = vertex2.subtract(vertex1).length();
  25216. dist = vectlg + vTotalDistance[i];
  25217. vTotalDistance[i] = dist;
  25218. }
  25219. }
  25220. // uvs
  25221. var u;
  25222. var v;
  25223. if (customUV) {
  25224. for (p = 0; p < customUV.length; p++) {
  25225. uvs.push(customUV[p].x, customUV[p].y);
  25226. }
  25227. }
  25228. else {
  25229. for (p = 0; p < pathArray.length; p++) {
  25230. for (i = 0; i < minlg + closePathCorr; i++) {
  25231. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25232. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25233. if (invertUV) {
  25234. uvs.push(v, u);
  25235. }
  25236. else {
  25237. uvs.push(u, v);
  25238. }
  25239. }
  25240. }
  25241. }
  25242. // indices
  25243. p = 0; // path index
  25244. var pi = 0; // positions array index
  25245. var l1 = lg[p] - 1; // path1 length
  25246. var l2 = lg[p + 1] - 1; // path2 length
  25247. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25248. var shft = idx[1] - idx[0]; // shift
  25249. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25250. while (pi <= min && p < path1nb) {
  25251. // 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
  25252. indices.push(pi, pi + shft, pi + 1);
  25253. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25254. pi += 1;
  25255. if (pi === min) {
  25256. p++;
  25257. if (p === lg.length - 1) {
  25258. shft = idx[0] - idx[p];
  25259. l1 = lg[p] - 1;
  25260. l2 = lg[0] - 1;
  25261. }
  25262. else {
  25263. shft = idx[p + 1] - idx[p];
  25264. l1 = lg[p] - 1;
  25265. l2 = lg[p + 1] - 1;
  25266. }
  25267. pi = idx[p];
  25268. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25269. }
  25270. }
  25271. // normals
  25272. VertexData.ComputeNormals(positions, indices, normals);
  25273. if (closePath) {
  25274. var indexFirst = 0;
  25275. var indexLast = 0;
  25276. for (p = 0; p < pathArray.length; p++) {
  25277. indexFirst = idx[p] * 3;
  25278. if (p + 1 < pathArray.length) {
  25279. indexLast = (idx[p + 1] - 1) * 3;
  25280. }
  25281. else {
  25282. indexLast = normals.length - 3;
  25283. }
  25284. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25285. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25286. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25287. normals[indexLast] = normals[indexFirst];
  25288. normals[indexLast + 1] = normals[indexFirst + 1];
  25289. normals[indexLast + 2] = normals[indexFirst + 2];
  25290. }
  25291. }
  25292. // sides
  25293. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25294. // Colors
  25295. if (customColors) {
  25296. var colors = new Float32Array(customColors.length * 4);
  25297. for (var c = 0; c < customColors.length; c++) {
  25298. colors[c * 4] = customColors[c].r;
  25299. colors[c * 4 + 1] = customColors[c].g;
  25300. colors[c * 4 + 2] = customColors[c].b;
  25301. colors[c * 4 + 3] = customColors[c].a;
  25302. }
  25303. }
  25304. // Result
  25305. var vertexData = new VertexData();
  25306. var positions32 = new Float32Array(positions);
  25307. var normals32 = new Float32Array(normals);
  25308. var uvs32 = new Float32Array(uvs);
  25309. vertexData.indices = indices;
  25310. vertexData.positions = positions32;
  25311. vertexData.normals = normals32;
  25312. vertexData.uvs = uvs32;
  25313. if (customColors) {
  25314. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25315. }
  25316. if (closePath) {
  25317. vertexData._idx = idx;
  25318. }
  25319. return vertexData;
  25320. };
  25321. /**
  25322. * Creates the VertexData of the Box.
  25323. */
  25324. VertexData.CreateBox = function (options) {
  25325. var normalsSource = [
  25326. new BABYLON.Vector3(0, 0, 1),
  25327. new BABYLON.Vector3(0, 0, -1),
  25328. new BABYLON.Vector3(1, 0, 0),
  25329. new BABYLON.Vector3(-1, 0, 0),
  25330. new BABYLON.Vector3(0, 1, 0),
  25331. new BABYLON.Vector3(0, -1, 0)
  25332. ];
  25333. var indices = [];
  25334. var positions = [];
  25335. var normals = [];
  25336. var uvs = [];
  25337. var width = options.width || options.size || 1;
  25338. var height = options.height || options.size || 1;
  25339. var depth = options.depth || options.size || 1;
  25340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25341. var faceUV = options.faceUV || new Array(6);
  25342. var faceColors = options.faceColors;
  25343. var colors = [];
  25344. // default face colors and UV if undefined
  25345. for (var f = 0; f < 6; f++) {
  25346. if (faceUV[f] === undefined) {
  25347. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25348. }
  25349. if (faceColors && faceColors[f] === undefined) {
  25350. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25351. }
  25352. }
  25353. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25354. // Create each face in turn.
  25355. for (var index = 0; index < normalsSource.length; index++) {
  25356. var normal = normalsSource[index];
  25357. // Get two vectors perpendicular to the face normal and to each other.
  25358. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25359. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25360. // Six indices (two triangles) per face.
  25361. var verticesLength = positions.length / 3;
  25362. indices.push(verticesLength);
  25363. indices.push(verticesLength + 1);
  25364. indices.push(verticesLength + 2);
  25365. indices.push(verticesLength);
  25366. indices.push(verticesLength + 2);
  25367. indices.push(verticesLength + 3);
  25368. // Four vertices per face.
  25369. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25370. positions.push(vertex.x, vertex.y, vertex.z);
  25371. normals.push(normal.x, normal.y, normal.z);
  25372. uvs.push(faceUV[index].z, faceUV[index].w);
  25373. if (faceColors) {
  25374. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25375. }
  25376. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25377. positions.push(vertex.x, vertex.y, vertex.z);
  25378. normals.push(normal.x, normal.y, normal.z);
  25379. uvs.push(faceUV[index].x, faceUV[index].w);
  25380. if (faceColors) {
  25381. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25382. }
  25383. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25384. positions.push(vertex.x, vertex.y, vertex.z);
  25385. normals.push(normal.x, normal.y, normal.z);
  25386. uvs.push(faceUV[index].x, faceUV[index].y);
  25387. if (faceColors) {
  25388. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25389. }
  25390. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25391. positions.push(vertex.x, vertex.y, vertex.z);
  25392. normals.push(normal.x, normal.y, normal.z);
  25393. uvs.push(faceUV[index].z, faceUV[index].y);
  25394. if (faceColors) {
  25395. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25396. }
  25397. }
  25398. // sides
  25399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25400. // Result
  25401. var vertexData = new VertexData();
  25402. vertexData.indices = indices;
  25403. vertexData.positions = positions;
  25404. vertexData.normals = normals;
  25405. vertexData.uvs = uvs;
  25406. if (faceColors) {
  25407. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25408. vertexData.colors = totalColors;
  25409. }
  25410. return vertexData;
  25411. };
  25412. /**
  25413. * Creates the VertexData of the Sphere.
  25414. */
  25415. VertexData.CreateSphere = function (options) {
  25416. var segments = options.segments || 32;
  25417. var diameterX = options.diameterX || options.diameter || 1;
  25418. var diameterY = options.diameterY || options.diameter || 1;
  25419. var diameterZ = options.diameterZ || options.diameter || 1;
  25420. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25421. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25422. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25423. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25424. var totalZRotationSteps = 2 + segments;
  25425. var totalYRotationSteps = 2 * totalZRotationSteps;
  25426. var indices = [];
  25427. var positions = [];
  25428. var normals = [];
  25429. var uvs = [];
  25430. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25431. var normalizedZ = zRotationStep / totalZRotationSteps;
  25432. var angleZ = normalizedZ * Math.PI * slice;
  25433. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25434. var normalizedY = yRotationStep / totalYRotationSteps;
  25435. var angleY = normalizedY * Math.PI * 2 * arc;
  25436. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25437. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25438. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25439. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25440. var vertex = complete.multiply(radius);
  25441. var normal = complete.divide(radius).normalize();
  25442. positions.push(vertex.x, vertex.y, vertex.z);
  25443. normals.push(normal.x, normal.y, normal.z);
  25444. uvs.push(normalizedY, normalizedZ);
  25445. }
  25446. if (zRotationStep > 0) {
  25447. var verticesCount = positions.length / 3;
  25448. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25449. indices.push((firstIndex));
  25450. indices.push((firstIndex + 1));
  25451. indices.push(firstIndex + totalYRotationSteps + 1);
  25452. indices.push((firstIndex + totalYRotationSteps + 1));
  25453. indices.push((firstIndex + 1));
  25454. indices.push((firstIndex + totalYRotationSteps + 2));
  25455. }
  25456. }
  25457. }
  25458. // Sides
  25459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25460. // Result
  25461. var vertexData = new VertexData();
  25462. vertexData.indices = indices;
  25463. vertexData.positions = positions;
  25464. vertexData.normals = normals;
  25465. vertexData.uvs = uvs;
  25466. return vertexData;
  25467. };
  25468. /**
  25469. * Creates the VertexData of the Cylinder or Cone.
  25470. */
  25471. VertexData.CreateCylinder = function (options) {
  25472. var height = options.height || 2;
  25473. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25474. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25475. var tessellation = options.tessellation || 24;
  25476. var subdivisions = options.subdivisions || 1;
  25477. var hasRings = options.hasRings;
  25478. var enclose = options.enclose;
  25479. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25480. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25481. var faceUV = options.faceUV || new Array(3);
  25482. var faceColors = options.faceColors;
  25483. // default face colors and UV if undefined
  25484. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25485. var ringNb = (hasRings) ? subdivisions : 1;
  25486. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25487. var f;
  25488. for (f = 0; f < surfaceNb; f++) {
  25489. if (faceColors && faceColors[f] === undefined) {
  25490. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25491. }
  25492. }
  25493. for (f = 0; f < surfaceNb; f++) {
  25494. if (faceUV && faceUV[f] === undefined) {
  25495. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25496. }
  25497. }
  25498. var indices = [];
  25499. var positions = [];
  25500. var normals = [];
  25501. var uvs = [];
  25502. var colors = [];
  25503. var angle_step = Math.PI * 2 * arc / tessellation;
  25504. var angle;
  25505. var h;
  25506. var radius;
  25507. var tan = (diameterBottom - diameterTop) / 2 / height;
  25508. var ringVertex = BABYLON.Vector3.Zero();
  25509. var ringNormal = BABYLON.Vector3.Zero();
  25510. var ringFirstVertex = BABYLON.Vector3.Zero();
  25511. var ringFirstNormal = BABYLON.Vector3.Zero();
  25512. var quadNormal = BABYLON.Vector3.Zero();
  25513. var Y = BABYLON.Axis.Y;
  25514. // positions, normals, uvs
  25515. var i;
  25516. var j;
  25517. var r;
  25518. var ringIdx = 1;
  25519. var s = 1; // surface index
  25520. var cs = 0;
  25521. var v = 0;
  25522. for (i = 0; i <= subdivisions; i++) {
  25523. h = i / subdivisions;
  25524. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25525. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25526. for (r = 0; r < ringIdx; r++) {
  25527. if (hasRings) {
  25528. s += r;
  25529. }
  25530. if (enclose) {
  25531. s += 2 * r;
  25532. }
  25533. for (j = 0; j <= tessellation; j++) {
  25534. angle = j * angle_step;
  25535. // position
  25536. ringVertex.x = Math.cos(-angle) * radius;
  25537. ringVertex.y = -height / 2 + h * height;
  25538. ringVertex.z = Math.sin(-angle) * radius;
  25539. // normal
  25540. if (diameterTop === 0 && i === subdivisions) {
  25541. // if no top cap, reuse former normals
  25542. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25543. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25544. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25545. }
  25546. else {
  25547. ringNormal.x = ringVertex.x;
  25548. ringNormal.z = ringVertex.z;
  25549. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25550. ringNormal.normalize();
  25551. }
  25552. // keep first ring vertex values for enclose
  25553. if (j === 0) {
  25554. ringFirstVertex.copyFrom(ringVertex);
  25555. ringFirstNormal.copyFrom(ringNormal);
  25556. }
  25557. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25558. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25559. if (hasRings) {
  25560. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25561. }
  25562. else {
  25563. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25564. }
  25565. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25566. if (faceColors) {
  25567. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25568. }
  25569. }
  25570. // if enclose, add four vertices and their dedicated normals
  25571. if (arc !== 1 && enclose) {
  25572. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25573. positions.push(0, ringVertex.y, 0);
  25574. positions.push(0, ringVertex.y, 0);
  25575. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25576. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25577. quadNormal.normalize();
  25578. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25579. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25580. quadNormal.normalize();
  25581. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25582. if (hasRings) {
  25583. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25584. }
  25585. else {
  25586. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25587. }
  25588. uvs.push(faceUV[s + 1].x, v);
  25589. uvs.push(faceUV[s + 1].z, v);
  25590. if (hasRings) {
  25591. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25592. }
  25593. else {
  25594. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25595. }
  25596. uvs.push(faceUV[s + 2].x, v);
  25597. uvs.push(faceUV[s + 2].z, v);
  25598. if (faceColors) {
  25599. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25600. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25601. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25602. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25603. }
  25604. }
  25605. if (cs !== s) {
  25606. cs = s;
  25607. }
  25608. }
  25609. }
  25610. // indices
  25611. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25612. var s;
  25613. i = 0;
  25614. for (s = 0; s < subdivisions; s++) {
  25615. for (j = 0; j < tessellation; j++) {
  25616. var i0 = i * (e + 1) + j;
  25617. var i1 = (i + 1) * (e + 1) + j;
  25618. var i2 = i * (e + 1) + (j + 1);
  25619. var i3 = (i + 1) * (e + 1) + (j + 1);
  25620. indices.push(i0, i1, i2);
  25621. indices.push(i3, i2, i1);
  25622. }
  25623. if (arc !== 1 && enclose) {
  25624. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25625. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25626. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25627. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25628. }
  25629. i = (hasRings) ? (i + 2) : (i + 1);
  25630. }
  25631. // Caps
  25632. var createCylinderCap = function (isTop) {
  25633. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25634. if (radius === 0) {
  25635. return;
  25636. }
  25637. // Cap positions, normals & uvs
  25638. var angle;
  25639. var circleVector;
  25640. var i;
  25641. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25642. var c;
  25643. if (faceColors) {
  25644. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25645. }
  25646. // cap center
  25647. var vbase = positions.length / 3;
  25648. var offset = isTop ? height / 2 : -height / 2;
  25649. var center = new BABYLON.Vector3(0, offset, 0);
  25650. positions.push(center.x, center.y, center.z);
  25651. normals.push(0, isTop ? 1 : -1, 0);
  25652. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25653. if (faceColors) {
  25654. colors.push(c.r, c.g, c.b, c.a);
  25655. }
  25656. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25657. for (i = 0; i <= tessellation; i++) {
  25658. angle = Math.PI * 2 * i * arc / tessellation;
  25659. var cos = Math.cos(-angle);
  25660. var sin = Math.sin(-angle);
  25661. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25662. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25663. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25664. normals.push(0, isTop ? 1 : -1, 0);
  25665. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25666. if (faceColors) {
  25667. colors.push(c.r, c.g, c.b, c.a);
  25668. }
  25669. }
  25670. // Cap indices
  25671. for (i = 0; i < tessellation; i++) {
  25672. if (!isTop) {
  25673. indices.push(vbase);
  25674. indices.push(vbase + (i + 1));
  25675. indices.push(vbase + (i + 2));
  25676. }
  25677. else {
  25678. indices.push(vbase);
  25679. indices.push(vbase + (i + 2));
  25680. indices.push(vbase + (i + 1));
  25681. }
  25682. }
  25683. };
  25684. // add caps to geometry
  25685. createCylinderCap(false);
  25686. createCylinderCap(true);
  25687. // Sides
  25688. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25689. var vertexData = new VertexData();
  25690. vertexData.indices = indices;
  25691. vertexData.positions = positions;
  25692. vertexData.normals = normals;
  25693. vertexData.uvs = uvs;
  25694. if (faceColors) {
  25695. vertexData.colors = colors;
  25696. }
  25697. return vertexData;
  25698. };
  25699. /**
  25700. * Creates the VertexData of the Torus.
  25701. */
  25702. VertexData.CreateTorus = function (options) {
  25703. var indices = [];
  25704. var positions = [];
  25705. var normals = [];
  25706. var uvs = [];
  25707. var diameter = options.diameter || 1;
  25708. var thickness = options.thickness || 0.5;
  25709. var tessellation = options.tessellation || 16;
  25710. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25711. var stride = tessellation + 1;
  25712. for (var i = 0; i <= tessellation; i++) {
  25713. var u = i / tessellation;
  25714. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25715. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25716. for (var j = 0; j <= tessellation; j++) {
  25717. var v = 1 - j / tessellation;
  25718. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25719. var dx = Math.cos(innerAngle);
  25720. var dy = Math.sin(innerAngle);
  25721. // Create a vertex.
  25722. var normal = new BABYLON.Vector3(dx, dy, 0);
  25723. var position = normal.scale(thickness / 2);
  25724. var textureCoordinate = new BABYLON.Vector2(u, v);
  25725. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25726. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25727. positions.push(position.x, position.y, position.z);
  25728. normals.push(normal.x, normal.y, normal.z);
  25729. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25730. // And create indices for two triangles.
  25731. var nextI = (i + 1) % stride;
  25732. var nextJ = (j + 1) % stride;
  25733. indices.push(i * stride + j);
  25734. indices.push(i * stride + nextJ);
  25735. indices.push(nextI * stride + j);
  25736. indices.push(i * stride + nextJ);
  25737. indices.push(nextI * stride + nextJ);
  25738. indices.push(nextI * stride + j);
  25739. }
  25740. }
  25741. // Sides
  25742. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25743. // Result
  25744. var vertexData = new VertexData();
  25745. vertexData.indices = indices;
  25746. vertexData.positions = positions;
  25747. vertexData.normals = normals;
  25748. vertexData.uvs = uvs;
  25749. return vertexData;
  25750. };
  25751. /**
  25752. * Creates the VertexData of the LineSystem.
  25753. */
  25754. VertexData.CreateLineSystem = function (options) {
  25755. var indices = [];
  25756. var positions = [];
  25757. var lines = options.lines;
  25758. var idx = 0;
  25759. for (var l = 0; l < lines.length; l++) {
  25760. var points = lines[l];
  25761. for (var index = 0; index < points.length; index++) {
  25762. positions.push(points[index].x, points[index].y, points[index].z);
  25763. if (index > 0) {
  25764. indices.push(idx - 1);
  25765. indices.push(idx);
  25766. }
  25767. idx++;
  25768. }
  25769. }
  25770. var vertexData = new VertexData();
  25771. vertexData.indices = indices;
  25772. vertexData.positions = positions;
  25773. return vertexData;
  25774. };
  25775. /**
  25776. * Create the VertexData of the DashedLines.
  25777. */
  25778. VertexData.CreateDashedLines = function (options) {
  25779. var dashSize = options.dashSize || 3;
  25780. var gapSize = options.gapSize || 1;
  25781. var dashNb = options.dashNb || 200;
  25782. var points = options.points;
  25783. var positions = new Array();
  25784. var indices = new Array();
  25785. var curvect = BABYLON.Vector3.Zero();
  25786. var lg = 0;
  25787. var nb = 0;
  25788. var shft = 0;
  25789. var dashshft = 0;
  25790. var curshft = 0;
  25791. var idx = 0;
  25792. var i = 0;
  25793. for (i = 0; i < points.length - 1; i++) {
  25794. points[i + 1].subtractToRef(points[i], curvect);
  25795. lg += curvect.length();
  25796. }
  25797. shft = lg / dashNb;
  25798. dashshft = dashSize * shft / (dashSize + gapSize);
  25799. for (i = 0; i < points.length - 1; i++) {
  25800. points[i + 1].subtractToRef(points[i], curvect);
  25801. nb = Math.floor(curvect.length() / shft);
  25802. curvect.normalize();
  25803. for (var j = 0; j < nb; j++) {
  25804. curshft = shft * j;
  25805. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25806. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25807. indices.push(idx, idx + 1);
  25808. idx += 2;
  25809. }
  25810. }
  25811. // Result
  25812. var vertexData = new VertexData();
  25813. vertexData.positions = positions;
  25814. vertexData.indices = indices;
  25815. return vertexData;
  25816. };
  25817. /**
  25818. * Creates the VertexData of the Ground.
  25819. */
  25820. VertexData.CreateGround = function (options) {
  25821. var indices = [];
  25822. var positions = [];
  25823. var normals = [];
  25824. var uvs = [];
  25825. var row, col;
  25826. var width = options.width || 1;
  25827. var height = options.height || 1;
  25828. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25829. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25830. for (row = 0; row <= subdivisionsY; row++) {
  25831. for (col = 0; col <= subdivisionsX; col++) {
  25832. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25833. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25834. positions.push(position.x, position.y, position.z);
  25835. normals.push(normal.x, normal.y, normal.z);
  25836. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25837. }
  25838. }
  25839. for (row = 0; row < subdivisionsY; row++) {
  25840. for (col = 0; col < subdivisionsX; col++) {
  25841. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25842. indices.push(col + 1 + row * (subdivisionsX + 1));
  25843. indices.push(col + row * (subdivisionsX + 1));
  25844. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25845. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25846. indices.push(col + row * (subdivisionsX + 1));
  25847. }
  25848. }
  25849. // Result
  25850. var vertexData = new VertexData();
  25851. vertexData.indices = indices;
  25852. vertexData.positions = positions;
  25853. vertexData.normals = normals;
  25854. vertexData.uvs = uvs;
  25855. return vertexData;
  25856. };
  25857. /**
  25858. * Creates the VertexData of the TiledGround.
  25859. */
  25860. VertexData.CreateTiledGround = function (options) {
  25861. var xmin = options.xmin || -1.0;
  25862. var zmin = options.zmin || -1.0;
  25863. var xmax = options.xmax || 1.0;
  25864. var zmax = options.zmax || 1.0;
  25865. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25866. var precision = options.precision || { w: 1, h: 1 };
  25867. var indices = [];
  25868. var positions = [];
  25869. var normals = [];
  25870. var uvs = [];
  25871. var row, col, tileRow, tileCol;
  25872. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25873. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25874. precision.w = (precision.w < 1) ? 1 : precision.w;
  25875. precision.h = (precision.h < 1) ? 1 : precision.h;
  25876. var tileSize = {
  25877. 'w': (xmax - xmin) / subdivisions.w,
  25878. 'h': (zmax - zmin) / subdivisions.h
  25879. };
  25880. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25881. // Indices
  25882. var base = positions.length / 3;
  25883. var rowLength = precision.w + 1;
  25884. for (row = 0; row < precision.h; row++) {
  25885. for (col = 0; col < precision.w; col++) {
  25886. var square = [
  25887. base + col + row * rowLength,
  25888. base + (col + 1) + row * rowLength,
  25889. base + (col + 1) + (row + 1) * rowLength,
  25890. base + col + (row + 1) * rowLength
  25891. ];
  25892. indices.push(square[1]);
  25893. indices.push(square[2]);
  25894. indices.push(square[3]);
  25895. indices.push(square[0]);
  25896. indices.push(square[1]);
  25897. indices.push(square[3]);
  25898. }
  25899. }
  25900. // Position, normals and uvs
  25901. var position = BABYLON.Vector3.Zero();
  25902. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25903. for (row = 0; row <= precision.h; row++) {
  25904. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25905. for (col = 0; col <= precision.w; col++) {
  25906. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25907. position.y = 0;
  25908. positions.push(position.x, position.y, position.z);
  25909. normals.push(normal.x, normal.y, normal.z);
  25910. uvs.push(col / precision.w, row / precision.h);
  25911. }
  25912. }
  25913. }
  25914. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25915. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25916. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25917. }
  25918. }
  25919. // Result
  25920. var vertexData = new VertexData();
  25921. vertexData.indices = indices;
  25922. vertexData.positions = positions;
  25923. vertexData.normals = normals;
  25924. vertexData.uvs = uvs;
  25925. return vertexData;
  25926. };
  25927. /**
  25928. * Creates the VertexData of the Ground designed from a heightmap.
  25929. */
  25930. VertexData.CreateGroundFromHeightMap = function (options) {
  25931. var indices = [];
  25932. var positions = [];
  25933. var normals = [];
  25934. var uvs = [];
  25935. var row, col;
  25936. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25937. // Vertices
  25938. for (row = 0; row <= options.subdivisions; row++) {
  25939. for (col = 0; col <= options.subdivisions; col++) {
  25940. 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));
  25941. // Compute height
  25942. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25943. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25944. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25945. var r = options.buffer[pos] / 255.0;
  25946. var g = options.buffer[pos + 1] / 255.0;
  25947. var b = options.buffer[pos + 2] / 255.0;
  25948. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25949. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25950. // Add vertex
  25951. positions.push(position.x, position.y, position.z);
  25952. normals.push(0, 0, 0);
  25953. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25954. }
  25955. }
  25956. // Indices
  25957. for (row = 0; row < options.subdivisions; row++) {
  25958. for (col = 0; col < options.subdivisions; col++) {
  25959. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25960. indices.push(col + 1 + row * (options.subdivisions + 1));
  25961. indices.push(col + row * (options.subdivisions + 1));
  25962. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25963. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25964. indices.push(col + row * (options.subdivisions + 1));
  25965. }
  25966. }
  25967. // Normals
  25968. VertexData.ComputeNormals(positions, indices, normals);
  25969. // Result
  25970. var vertexData = new VertexData();
  25971. vertexData.indices = indices;
  25972. vertexData.positions = positions;
  25973. vertexData.normals = normals;
  25974. vertexData.uvs = uvs;
  25975. return vertexData;
  25976. };
  25977. /**
  25978. * Creates the VertexData of the Plane.
  25979. */
  25980. VertexData.CreatePlane = function (options) {
  25981. var indices = [];
  25982. var positions = [];
  25983. var normals = [];
  25984. var uvs = [];
  25985. var width = options.width || options.size || 1;
  25986. var height = options.height || options.size || 1;
  25987. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25988. // Vertices
  25989. var halfWidth = width / 2.0;
  25990. var halfHeight = height / 2.0;
  25991. positions.push(-halfWidth, -halfHeight, 0);
  25992. normals.push(0, 0, -1.0);
  25993. uvs.push(0.0, 0.0);
  25994. positions.push(halfWidth, -halfHeight, 0);
  25995. normals.push(0, 0, -1.0);
  25996. uvs.push(1.0, 0.0);
  25997. positions.push(halfWidth, halfHeight, 0);
  25998. normals.push(0, 0, -1.0);
  25999. uvs.push(1.0, 1.0);
  26000. positions.push(-halfWidth, halfHeight, 0);
  26001. normals.push(0, 0, -1.0);
  26002. uvs.push(0.0, 1.0);
  26003. // Indices
  26004. indices.push(0);
  26005. indices.push(1);
  26006. indices.push(2);
  26007. indices.push(0);
  26008. indices.push(2);
  26009. indices.push(3);
  26010. // Sides
  26011. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26012. // Result
  26013. var vertexData = new VertexData();
  26014. vertexData.indices = indices;
  26015. vertexData.positions = positions;
  26016. vertexData.normals = normals;
  26017. vertexData.uvs = uvs;
  26018. return vertexData;
  26019. };
  26020. /**
  26021. * Creates the VertexData of the Disc or regular Polygon.
  26022. */
  26023. VertexData.CreateDisc = function (options) {
  26024. var positions = [];
  26025. var indices = [];
  26026. var normals = [];
  26027. var uvs = [];
  26028. var radius = options.radius || 0.5;
  26029. var tessellation = options.tessellation || 64;
  26030. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26031. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26032. // positions and uvs
  26033. positions.push(0, 0, 0); // disc center first
  26034. uvs.push(0.5, 0.5);
  26035. var theta = Math.PI * 2 * arc;
  26036. var step = theta / tessellation;
  26037. for (var a = 0; a < theta; a += step) {
  26038. var x = Math.cos(a);
  26039. var y = Math.sin(a);
  26040. var u = (x + 1) / 2;
  26041. var v = (1 - y) / 2;
  26042. positions.push(radius * x, radius * y, 0);
  26043. uvs.push(u, v);
  26044. }
  26045. if (arc === 1) {
  26046. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26047. uvs.push(uvs[2], uvs[3]);
  26048. }
  26049. //indices
  26050. var vertexNb = positions.length / 3;
  26051. for (var i = 1; i < vertexNb - 1; i++) {
  26052. indices.push(i + 1, 0, i);
  26053. }
  26054. // result
  26055. VertexData.ComputeNormals(positions, indices, normals);
  26056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26057. var vertexData = new VertexData();
  26058. vertexData.indices = indices;
  26059. vertexData.positions = positions;
  26060. vertexData.normals = normals;
  26061. vertexData.uvs = uvs;
  26062. return vertexData;
  26063. };
  26064. /**
  26065. * Re-creates the VertexData of the Polygon for sideOrientation.
  26066. */
  26067. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26068. var faceUV = fUV || new Array(3);
  26069. var faceColors = fColors;
  26070. var colors = [];
  26071. // default face colors and UV if undefined
  26072. for (var f = 0; f < 3; f++) {
  26073. if (faceUV[f] === undefined) {
  26074. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26075. }
  26076. if (faceColors && faceColors[f] === undefined) {
  26077. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26078. }
  26079. }
  26080. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26081. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26082. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26083. var indices = polygon.getIndices();
  26084. // set face colours and textures
  26085. var idx = 0;
  26086. var face = 0;
  26087. for (var index = 0; index < normals.length; index += 3) {
  26088. //Edge Face no. 1
  26089. if (Math.abs(normals[index + 1]) == 0) {
  26090. face = 1;
  26091. }
  26092. //Top Face no. 0
  26093. if (normals[index + 1] == 1) {
  26094. face = 0;
  26095. }
  26096. //Bottom Face no. 2
  26097. if (normals[index + 1] == -1) {
  26098. face = 2;
  26099. }
  26100. idx = index / 3;
  26101. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26102. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26103. if (faceColors) {
  26104. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26105. }
  26106. }
  26107. // sides
  26108. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26109. // Result
  26110. var vertexData = new VertexData();
  26111. vertexData.indices = indices;
  26112. vertexData.positions = positions;
  26113. vertexData.normals = normals;
  26114. vertexData.uvs = uvs;
  26115. if (faceColors) {
  26116. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26117. vertexData.colors = totalColors;
  26118. }
  26119. return vertexData;
  26120. };
  26121. /**
  26122. * Creates the VertexData of the IcoSphere.
  26123. */
  26124. VertexData.CreateIcoSphere = function (options) {
  26125. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26126. var radius = options.radius || 1;
  26127. var flat = (options.flat === undefined) ? true : options.flat;
  26128. var subdivisions = options.subdivisions || 4;
  26129. var radiusX = options.radiusX || radius;
  26130. var radiusY = options.radiusY || radius;
  26131. var radiusZ = options.radiusZ || radius;
  26132. var t = (1 + Math.sqrt(5)) / 2;
  26133. // 12 vertex x,y,z
  26134. var ico_vertices = [
  26135. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26136. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26137. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26138. ];
  26139. // index of 3 vertex makes a face of icopshere
  26140. var ico_indices = [
  26141. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26142. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26143. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26144. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26145. ];
  26146. // vertex for uv have aliased position, not for UV
  26147. var vertices_unalias_id = [
  26148. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26149. // vertex alias
  26150. 0,
  26151. 2,
  26152. 3,
  26153. 3,
  26154. 3,
  26155. 4,
  26156. 7,
  26157. 8,
  26158. 9,
  26159. 9,
  26160. 10,
  26161. 11 // 23: B + 12
  26162. ];
  26163. // uv as integer step (not pixels !)
  26164. var ico_vertexuv = [
  26165. 5, 1, 3, 1, 6, 4, 0, 0,
  26166. 5, 3, 4, 2, 2, 2, 4, 0,
  26167. 2, 0, 1, 1, 6, 0, 6, 2,
  26168. // vertex alias (for same vertex on different faces)
  26169. 0, 4,
  26170. 3, 3,
  26171. 4, 4,
  26172. 3, 1,
  26173. 4, 2,
  26174. 4, 4,
  26175. 0, 2,
  26176. 1, 1,
  26177. 2, 2,
  26178. 3, 3,
  26179. 1, 3,
  26180. 2, 4 // 23: B + 12
  26181. ];
  26182. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26183. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26184. // First island of uv mapping
  26185. // v = 4h 3+ 2
  26186. // v = 3h 9+ 4
  26187. // v = 2h 9+ 5 B
  26188. // v = 1h 9 1 0
  26189. // v = 0h 3 8 7 A
  26190. // u = 0 1 2 3 4 5 6 *a
  26191. // Second island of uv mapping
  26192. // v = 4h 0+ B+ 4+
  26193. // v = 3h A+ 2+
  26194. // v = 2h 7+ 6 3+
  26195. // v = 1h 8+ 3+
  26196. // v = 0h
  26197. // u = 0 1 2 3 4 5 6 *a
  26198. // Face layout on texture UV mapping
  26199. // ============
  26200. // \ 4 /\ 16 / ======
  26201. // \ / \ / /\ 11 /
  26202. // \/ 7 \/ / \ /
  26203. // ======= / 10 \/
  26204. // /\ 17 /\ =======
  26205. // / \ / \ \ 15 /\
  26206. // / 8 \/ 12 \ \ / \
  26207. // ============ \/ 6 \
  26208. // \ 18 /\ ============
  26209. // \ / \ \ 5 /\ 0 /
  26210. // \/ 13 \ \ / \ /
  26211. // ======= \/ 1 \/
  26212. // =============
  26213. // /\ 19 /\ 2 /\
  26214. // / \ / \ / \
  26215. // / 14 \/ 9 \/ 3 \
  26216. // ===================
  26217. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26218. var ustep = 138 / 1024;
  26219. var vstep = 239 / 1024;
  26220. var uoffset = 60 / 1024;
  26221. var voffset = 26 / 1024;
  26222. // Second island should have margin, not to touch the first island
  26223. // avoid any borderline artefact in pixel rounding
  26224. var island_u_offset = -40 / 1024;
  26225. var island_v_offset = +20 / 1024;
  26226. // face is either island 0 or 1 :
  26227. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26228. var island = [
  26229. 0, 0, 0, 0, 1,
  26230. 0, 0, 1, 1, 0,
  26231. 0, 0, 1, 1, 0,
  26232. 0, 1, 1, 1, 0 // 15 - 19
  26233. ];
  26234. var indices = [];
  26235. var positions = [];
  26236. var normals = [];
  26237. var uvs = [];
  26238. var current_indice = 0;
  26239. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26240. var face_vertex_pos = new Array(3);
  26241. var face_vertex_uv = new Array(3);
  26242. var v012;
  26243. for (v012 = 0; v012 < 3; v012++) {
  26244. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26245. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26246. }
  26247. // create all with normals
  26248. for (var face = 0; face < 20; face++) {
  26249. // 3 vertex per face
  26250. for (v012 = 0; v012 < 3; v012++) {
  26251. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26252. var v_id = ico_indices[3 * face + v012];
  26253. // vertex have 3D position (x,y,z)
  26254. 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]);
  26255. // Normalize to get normal, then scale to radius
  26256. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26257. // uv Coordinates from vertex ID
  26258. 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);
  26259. }
  26260. // Subdivide the face (interpolate pos, norm, uv)
  26261. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26262. // - norm is linear interpolation of vertex corner normal
  26263. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26264. // - uv is linear interpolation
  26265. //
  26266. // Topology is as below for sub-divide by 2
  26267. // vertex shown as v0,v1,v2
  26268. // interp index is i1 to progress in range [v0,v1[
  26269. // interp index is i2 to progress in range [v0,v2[
  26270. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26271. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26272. //
  26273. //
  26274. // i2 v2
  26275. // ^ ^
  26276. // / / \
  26277. // / / \
  26278. // / / \
  26279. // / / (0,1) \
  26280. // / #---------\
  26281. // / / \ (0,0)'/ \
  26282. // / / \ / \
  26283. // / / \ / \
  26284. // / / (0,0) \ / (1,0) \
  26285. // / #---------#---------\
  26286. // v0 v1
  26287. //
  26288. // --------------------> i1
  26289. //
  26290. // interp of (i1,i2):
  26291. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26292. // along i1 : lerp(x0,x1, i1/(S-i2))
  26293. //
  26294. // centroid of triangle is needed to get help normal computation
  26295. // (c1,c2) are used for centroid location
  26296. var interp_vertex = function (i1, i2, c1, c2) {
  26297. // vertex is interpolated from
  26298. // - face_vertex_pos[0..2]
  26299. // - face_vertex_uv[0..2]
  26300. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26301. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26302. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26303. pos_interp.normalize();
  26304. var vertex_normal;
  26305. if (flat) {
  26306. // in flat mode, recalculate normal as face centroid normal
  26307. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26308. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26309. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26310. }
  26311. else {
  26312. // in smooth mode, recalculate normal from each single vertex position
  26313. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26314. }
  26315. // Vertex normal need correction due to X,Y,Z radius scaling
  26316. vertex_normal.x /= radiusX;
  26317. vertex_normal.y /= radiusY;
  26318. vertex_normal.z /= radiusZ;
  26319. vertex_normal.normalize();
  26320. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26321. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26322. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26323. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26324. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26325. uvs.push(uv_interp.x, uv_interp.y);
  26326. // push each vertex has member of a face
  26327. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26328. indices.push(current_indice);
  26329. current_indice++;
  26330. };
  26331. for (var i2 = 0; i2 < subdivisions; i2++) {
  26332. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26333. // face : (i1,i2) for /\ :
  26334. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26335. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26336. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26337. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26338. if (i1 + i2 + 1 < subdivisions) {
  26339. // face : (i1,i2)' for \/ :
  26340. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26341. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26342. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26343. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26344. }
  26345. }
  26346. }
  26347. }
  26348. // Sides
  26349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26350. // Result
  26351. var vertexData = new VertexData();
  26352. vertexData.indices = indices;
  26353. vertexData.positions = positions;
  26354. vertexData.normals = normals;
  26355. vertexData.uvs = uvs;
  26356. return vertexData;
  26357. };
  26358. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26359. /**
  26360. * Creates the VertexData of the Polyhedron.
  26361. */
  26362. VertexData.CreatePolyhedron = function (options) {
  26363. // provided polyhedron types :
  26364. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26365. // 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)
  26366. var polyhedra = [];
  26367. 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]] };
  26368. 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]] };
  26369. polyhedra[2] = {
  26370. 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]],
  26371. 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]]
  26372. };
  26373. polyhedra[3] = {
  26374. 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]],
  26375. 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]]
  26376. };
  26377. polyhedra[4] = {
  26378. 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]],
  26379. 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]]
  26380. };
  26381. 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]] };
  26382. 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]] };
  26383. 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]] };
  26384. 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]] };
  26385. 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]] };
  26386. 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]] };
  26387. 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]] };
  26388. 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]] };
  26389. 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]] };
  26390. polyhedra[14] = {
  26391. 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]],
  26392. 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]]
  26393. };
  26394. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26395. var size = options.size;
  26396. var sizeX = options.sizeX || size || 1;
  26397. var sizeY = options.sizeY || size || 1;
  26398. var sizeZ = options.sizeZ || size || 1;
  26399. var data = options.custom || polyhedra[type];
  26400. var nbfaces = data.face.length;
  26401. var faceUV = options.faceUV || new Array(nbfaces);
  26402. var faceColors = options.faceColors;
  26403. var flat = (options.flat === undefined) ? true : options.flat;
  26404. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26405. var positions = [];
  26406. var indices = [];
  26407. var normals = [];
  26408. var uvs = [];
  26409. var colors = [];
  26410. var index = 0;
  26411. var faceIdx = 0; // face cursor in the array "indexes"
  26412. var indexes = [];
  26413. var i = 0;
  26414. var f = 0;
  26415. var u, v, ang, x, y, tmp;
  26416. // default face colors and UV if undefined
  26417. if (flat) {
  26418. for (f = 0; f < nbfaces; f++) {
  26419. if (faceColors && faceColors[f] === undefined) {
  26420. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26421. }
  26422. if (faceUV && faceUV[f] === undefined) {
  26423. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26424. }
  26425. }
  26426. }
  26427. if (!flat) {
  26428. for (i = 0; i < data.vertex.length; i++) {
  26429. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26430. uvs.push(0, 0);
  26431. }
  26432. for (f = 0; f < nbfaces; f++) {
  26433. for (i = 0; i < data.face[f].length - 2; i++) {
  26434. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26435. }
  26436. }
  26437. }
  26438. else {
  26439. for (f = 0; f < nbfaces; f++) {
  26440. var fl = data.face[f].length; // number of vertices of the current face
  26441. ang = 2 * Math.PI / fl;
  26442. x = 0.5 * Math.tan(ang / 2);
  26443. y = 0.5;
  26444. // positions, uvs, colors
  26445. for (i = 0; i < fl; i++) {
  26446. // positions
  26447. 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);
  26448. indexes.push(index);
  26449. index++;
  26450. // uvs
  26451. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26452. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26453. uvs.push(u, v);
  26454. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26455. y = x * Math.sin(ang) + y * Math.cos(ang);
  26456. x = tmp;
  26457. // colors
  26458. if (faceColors) {
  26459. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26460. }
  26461. }
  26462. // indices from indexes
  26463. for (i = 0; i < fl - 2; i++) {
  26464. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26465. }
  26466. faceIdx += fl;
  26467. }
  26468. }
  26469. VertexData.ComputeNormals(positions, indices, normals);
  26470. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26471. var vertexData = new VertexData();
  26472. vertexData.positions = positions;
  26473. vertexData.indices = indices;
  26474. vertexData.normals = normals;
  26475. vertexData.uvs = uvs;
  26476. if (faceColors && flat) {
  26477. vertexData.colors = colors;
  26478. }
  26479. return vertexData;
  26480. };
  26481. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26482. /**
  26483. * Creates the VertexData of the Torus Knot.
  26484. */
  26485. VertexData.CreateTorusKnot = function (options) {
  26486. var indices = [];
  26487. var positions = [];
  26488. var normals = [];
  26489. var uvs = [];
  26490. var radius = options.radius || 2;
  26491. var tube = options.tube || 0.5;
  26492. var radialSegments = options.radialSegments || 32;
  26493. var tubularSegments = options.tubularSegments || 32;
  26494. var p = options.p || 2;
  26495. var q = options.q || 3;
  26496. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26497. // Helper
  26498. var getPos = function (angle) {
  26499. var cu = Math.cos(angle);
  26500. var su = Math.sin(angle);
  26501. var quOverP = q / p * angle;
  26502. var cs = Math.cos(quOverP);
  26503. var tx = radius * (2 + cs) * 0.5 * cu;
  26504. var ty = radius * (2 + cs) * su * 0.5;
  26505. var tz = radius * Math.sin(quOverP) * 0.5;
  26506. return new BABYLON.Vector3(tx, ty, tz);
  26507. };
  26508. // Vertices
  26509. var i;
  26510. var j;
  26511. for (i = 0; i <= radialSegments; i++) {
  26512. var modI = i % radialSegments;
  26513. var u = modI / radialSegments * 2 * p * Math.PI;
  26514. var p1 = getPos(u);
  26515. var p2 = getPos(u + 0.01);
  26516. var tang = p2.subtract(p1);
  26517. var n = p2.add(p1);
  26518. var bitan = BABYLON.Vector3.Cross(tang, n);
  26519. n = BABYLON.Vector3.Cross(bitan, tang);
  26520. bitan.normalize();
  26521. n.normalize();
  26522. for (j = 0; j < tubularSegments; j++) {
  26523. var modJ = j % tubularSegments;
  26524. var v = modJ / tubularSegments * 2 * Math.PI;
  26525. var cx = -tube * Math.cos(v);
  26526. var cy = tube * Math.sin(v);
  26527. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26528. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26529. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26530. uvs.push(i / radialSegments);
  26531. uvs.push(j / tubularSegments);
  26532. }
  26533. }
  26534. for (i = 0; i < radialSegments; i++) {
  26535. for (j = 0; j < tubularSegments; j++) {
  26536. var jNext = (j + 1) % tubularSegments;
  26537. var a = i * tubularSegments + j;
  26538. var b = (i + 1) * tubularSegments + j;
  26539. var c = (i + 1) * tubularSegments + jNext;
  26540. var d = i * tubularSegments + jNext;
  26541. indices.push(d);
  26542. indices.push(b);
  26543. indices.push(a);
  26544. indices.push(d);
  26545. indices.push(c);
  26546. indices.push(b);
  26547. }
  26548. }
  26549. // Normals
  26550. VertexData.ComputeNormals(positions, indices, normals);
  26551. // Sides
  26552. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26553. // Result
  26554. var vertexData = new VertexData();
  26555. vertexData.indices = indices;
  26556. vertexData.positions = positions;
  26557. vertexData.normals = normals;
  26558. vertexData.uvs = uvs;
  26559. return vertexData;
  26560. };
  26561. // Tools
  26562. /**
  26563. * @param {any} - positions (number[] or Float32Array)
  26564. * @param {any} - indices (number[] or Uint16Array)
  26565. * @param {any} - normals (number[] or Float32Array)
  26566. * options (optional) :
  26567. * facetPositions : optional array of facet positions (vector3)
  26568. * facetNormals : optional array of facet normals (vector3)
  26569. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26570. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26571. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26572. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26573. * bInfo : optional bounding info, required for facetPartitioning computation
  26574. */
  26575. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26576. // temporary scalar variables
  26577. var index = 0; // facet index
  26578. var p1p2x = 0.0; // p1p2 vector x coordinate
  26579. var p1p2y = 0.0; // p1p2 vector y coordinate
  26580. var p1p2z = 0.0; // p1p2 vector z coordinate
  26581. var p3p2x = 0.0; // p3p2 vector x coordinate
  26582. var p3p2y = 0.0; // p3p2 vector y coordinate
  26583. var p3p2z = 0.0; // p3p2 vector z coordinate
  26584. var faceNormalx = 0.0; // facet normal x coordinate
  26585. var faceNormaly = 0.0; // facet normal y coordinate
  26586. var faceNormalz = 0.0; // facet normal z coordinate
  26587. var length = 0.0; // facet normal length before normalization
  26588. var v1x = 0; // vector1 x index in the positions array
  26589. var v1y = 0; // vector1 y index in the positions array
  26590. var v1z = 0; // vector1 z index in the positions array
  26591. var v2x = 0; // vector2 x index in the positions array
  26592. var v2y = 0; // vector2 y index in the positions array
  26593. var v2z = 0; // vector2 z index in the positions array
  26594. var v3x = 0; // vector3 x index in the positions array
  26595. var v3y = 0; // vector3 y index in the positions array
  26596. var v3z = 0; // vector3 z index in the positions array
  26597. var computeFacetNormals = false;
  26598. var computeFacetPositions = false;
  26599. var computeFacetPartitioning = false;
  26600. var faceNormalSign = 1;
  26601. if (options) {
  26602. computeFacetNormals = (options.facetNormals) ? true : false;
  26603. computeFacetPositions = (options.facetPositions) ? true : false;
  26604. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26605. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26606. }
  26607. // facetPartitioning reinit if needed
  26608. if (computeFacetPartitioning) {
  26609. var ox = 0; // X partitioning index for facet position
  26610. var oy = 0; // Y partinioning index for facet position
  26611. var oz = 0; // Z partinioning index for facet position
  26612. var b1x = 0; // X partitioning index for facet v1 vertex
  26613. var b1y = 0; // Y partitioning index for facet v1 vertex
  26614. var b1z = 0; // z partitioning index for facet v1 vertex
  26615. var b2x = 0; // X partitioning index for facet v2 vertex
  26616. var b2y = 0; // Y partitioning index for facet v2 vertex
  26617. var b2z = 0; // Z partitioning index for facet v2 vertex
  26618. var b3x = 0; // X partitioning index for facet v3 vertex
  26619. var b3y = 0; // Y partitioning index for facet v3 vertex
  26620. var b3z = 0; // Z partitioning index for facet v3 vertex
  26621. var block_idx_o = 0; // facet barycenter block index
  26622. var block_idx_v1 = 0; // v1 vertex block index
  26623. var block_idx_v2 = 0; // v2 vertex block index
  26624. var block_idx_v3 = 0; // v3 vertex block index
  26625. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26626. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26627. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26628. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26629. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26630. var subSq = options.subDiv.max * options.subDiv.max;
  26631. options.facetPartitioning.length = 0;
  26632. }
  26633. // reset the normals
  26634. for (index = 0; index < positions.length; index++) {
  26635. normals[index] = 0.0;
  26636. }
  26637. // Loop : 1 indice triplet = 1 facet
  26638. var nbFaces = indices.length / 3;
  26639. for (index = 0; index < nbFaces; index++) {
  26640. // get the indexes of the coordinates of each vertex of the facet
  26641. v1x = indices[index * 3] * 3;
  26642. v1y = v1x + 1;
  26643. v1z = v1x + 2;
  26644. v2x = indices[index * 3 + 1] * 3;
  26645. v2y = v2x + 1;
  26646. v2z = v2x + 2;
  26647. v3x = indices[index * 3 + 2] * 3;
  26648. v3y = v3x + 1;
  26649. v3z = v3x + 2;
  26650. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26651. p1p2y = positions[v1y] - positions[v2y];
  26652. p1p2z = positions[v1z] - positions[v2z];
  26653. p3p2x = positions[v3x] - positions[v2x];
  26654. p3p2y = positions[v3y] - positions[v2y];
  26655. p3p2z = positions[v3z] - positions[v2z];
  26656. // compute the face normal with the cross product
  26657. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26658. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26659. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26660. // normalize this normal and store it in the array facetData
  26661. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26662. length = (length === 0) ? 1.0 : length;
  26663. faceNormalx /= length;
  26664. faceNormaly /= length;
  26665. faceNormalz /= length;
  26666. if (computeFacetNormals) {
  26667. options.facetNormals[index].x = faceNormalx;
  26668. options.facetNormals[index].y = faceNormaly;
  26669. options.facetNormals[index].z = faceNormalz;
  26670. }
  26671. if (computeFacetPositions) {
  26672. // compute and the facet barycenter coordinates in the array facetPositions
  26673. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26674. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26675. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26676. }
  26677. if (computeFacetPartitioning) {
  26678. // store the facet indexes in arrays in the main facetPartitioning array :
  26679. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26680. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26681. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26682. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26683. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26684. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26685. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26686. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26687. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26688. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26689. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26690. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26691. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26692. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26693. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26694. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26695. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26696. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26697. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26698. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26699. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26700. // push each facet index in each block containing the vertex
  26701. options.facetPartitioning[block_idx_v1].push(index);
  26702. if (block_idx_v2 != block_idx_v1) {
  26703. options.facetPartitioning[block_idx_v2].push(index);
  26704. }
  26705. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26706. options.facetPartitioning[block_idx_v3].push(index);
  26707. }
  26708. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26709. options.facetPartitioning[block_idx_o].push(index);
  26710. }
  26711. }
  26712. // compute the normals anyway
  26713. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26714. normals[v1y] += faceNormaly;
  26715. normals[v1z] += faceNormalz;
  26716. normals[v2x] += faceNormalx;
  26717. normals[v2y] += faceNormaly;
  26718. normals[v2z] += faceNormalz;
  26719. normals[v3x] += faceNormalx;
  26720. normals[v3y] += faceNormaly;
  26721. normals[v3z] += faceNormalz;
  26722. }
  26723. // last normalization of each normal
  26724. for (index = 0; index < normals.length / 3; index++) {
  26725. faceNormalx = normals[index * 3];
  26726. faceNormaly = normals[index * 3 + 1];
  26727. faceNormalz = normals[index * 3 + 2];
  26728. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26729. length = (length === 0) ? 1.0 : length;
  26730. faceNormalx /= length;
  26731. faceNormaly /= length;
  26732. faceNormalz /= length;
  26733. normals[index * 3] = faceNormalx;
  26734. normals[index * 3 + 1] = faceNormaly;
  26735. normals[index * 3 + 2] = faceNormalz;
  26736. }
  26737. };
  26738. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26739. var li = indices.length;
  26740. var ln = normals.length;
  26741. var i;
  26742. var n;
  26743. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26744. switch (sideOrientation) {
  26745. case BABYLON.Mesh.FRONTSIDE:
  26746. // nothing changed
  26747. break;
  26748. case BABYLON.Mesh.BACKSIDE:
  26749. var tmp;
  26750. // indices
  26751. for (i = 0; i < li; i += 3) {
  26752. tmp = indices[i];
  26753. indices[i] = indices[i + 2];
  26754. indices[i + 2] = tmp;
  26755. }
  26756. // normals
  26757. for (n = 0; n < ln; n++) {
  26758. normals[n] = -normals[n];
  26759. }
  26760. break;
  26761. case BABYLON.Mesh.DOUBLESIDE:
  26762. // positions
  26763. var lp = positions.length;
  26764. var l = lp / 3;
  26765. for (var p = 0; p < lp; p++) {
  26766. positions[lp + p] = positions[p];
  26767. }
  26768. // indices
  26769. for (i = 0; i < li; i += 3) {
  26770. indices[i + li] = indices[i + 2] + l;
  26771. indices[i + 1 + li] = indices[i + 1] + l;
  26772. indices[i + 2 + li] = indices[i] + l;
  26773. }
  26774. // normals
  26775. for (n = 0; n < ln; n++) {
  26776. normals[ln + n] = -normals[n];
  26777. }
  26778. // uvs
  26779. var lu = uvs.length;
  26780. var u = 0;
  26781. for (u = 0; u < lu; u++) {
  26782. uvs[u + lu] = uvs[u];
  26783. }
  26784. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26785. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26786. u = 0;
  26787. for (i = 0; i < lu / 2; i++) {
  26788. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26789. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26790. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26791. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26792. u += 2;
  26793. }
  26794. break;
  26795. }
  26796. };
  26797. /**
  26798. * Creates a new VertexData from the imported parameters.
  26799. */
  26800. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26801. var vertexData = new VertexData();
  26802. // positions
  26803. var positions = parsedVertexData.positions;
  26804. if (positions) {
  26805. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26806. }
  26807. // normals
  26808. var normals = parsedVertexData.normals;
  26809. if (normals) {
  26810. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26811. }
  26812. // tangents
  26813. var tangents = parsedVertexData.tangents;
  26814. if (tangents) {
  26815. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26816. }
  26817. // uvs
  26818. var uvs = parsedVertexData.uvs;
  26819. if (uvs) {
  26820. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26821. }
  26822. // uv2s
  26823. var uv2s = parsedVertexData.uv2s;
  26824. if (uv2s) {
  26825. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26826. }
  26827. // uv3s
  26828. var uv3s = parsedVertexData.uv3s;
  26829. if (uv3s) {
  26830. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26831. }
  26832. // uv4s
  26833. var uv4s = parsedVertexData.uv4s;
  26834. if (uv4s) {
  26835. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26836. }
  26837. // uv5s
  26838. var uv5s = parsedVertexData.uv5s;
  26839. if (uv5s) {
  26840. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26841. }
  26842. // uv6s
  26843. var uv6s = parsedVertexData.uv6s;
  26844. if (uv6s) {
  26845. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26846. }
  26847. // colors
  26848. var colors = parsedVertexData.colors;
  26849. if (colors) {
  26850. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26851. }
  26852. // matricesIndices
  26853. var matricesIndices = parsedVertexData.matricesIndices;
  26854. if (matricesIndices) {
  26855. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26856. }
  26857. // matricesWeights
  26858. var matricesWeights = parsedVertexData.matricesWeights;
  26859. if (matricesWeights) {
  26860. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26861. }
  26862. // indices
  26863. var indices = parsedVertexData.indices;
  26864. if (indices) {
  26865. vertexData.indices = indices;
  26866. }
  26867. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26868. };
  26869. return VertexData;
  26870. }());
  26871. BABYLON.VertexData = VertexData;
  26872. })(BABYLON || (BABYLON = {}));
  26873. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26874. var BABYLON;
  26875. (function (BABYLON) {
  26876. var Geometry = (function () {
  26877. function Geometry(id, scene, vertexData, updatable, mesh) {
  26878. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26879. this._totalVertices = 0;
  26880. this._isDisposed = false;
  26881. this.id = id;
  26882. this._engine = scene.getEngine();
  26883. this._meshes = [];
  26884. this._scene = scene;
  26885. //Init vertex buffer cache
  26886. this._vertexBuffers = {};
  26887. this._indices = [];
  26888. // vertexData
  26889. if (vertexData) {
  26890. this.setAllVerticesData(vertexData, updatable);
  26891. }
  26892. else {
  26893. this._totalVertices = 0;
  26894. this._indices = [];
  26895. }
  26896. if (this._engine.getCaps().vertexArrayObject) {
  26897. this._vertexArrayObjects = {};
  26898. }
  26899. // applyToMesh
  26900. if (mesh) {
  26901. if (mesh.getClassName() === "LinesMesh") {
  26902. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26903. this.updateExtend();
  26904. }
  26905. this.applyToMesh(mesh);
  26906. mesh.computeWorldMatrix(true);
  26907. }
  26908. }
  26909. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26910. /**
  26911. * 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
  26912. * @returns The Bias Vector
  26913. */
  26914. get: function () {
  26915. return this._boundingBias;
  26916. },
  26917. set: function (value) {
  26918. if (this._boundingBias && this._boundingBias.equals(value)) {
  26919. return;
  26920. }
  26921. this._boundingBias = value.clone();
  26922. this.updateBoundingInfo(true, null);
  26923. },
  26924. enumerable: true,
  26925. configurable: true
  26926. });
  26927. Object.defineProperty(Geometry.prototype, "extend", {
  26928. get: function () {
  26929. return this._extend;
  26930. },
  26931. enumerable: true,
  26932. configurable: true
  26933. });
  26934. Geometry.prototype.getScene = function () {
  26935. return this._scene;
  26936. };
  26937. Geometry.prototype.getEngine = function () {
  26938. return this._engine;
  26939. };
  26940. Geometry.prototype.isReady = function () {
  26941. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26942. };
  26943. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26944. get: function () {
  26945. for (var index = 0; index < this._meshes.length; index++) {
  26946. if (!this._meshes[index].doNotSerialize) {
  26947. return false;
  26948. }
  26949. }
  26950. return true;
  26951. },
  26952. enumerable: true,
  26953. configurable: true
  26954. });
  26955. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26956. vertexData.applyToGeometry(this, updatable);
  26957. this.notifyUpdate();
  26958. };
  26959. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26960. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26961. this.setVerticesBuffer(buffer);
  26962. };
  26963. Geometry.prototype.removeVerticesData = function (kind) {
  26964. if (this._vertexBuffers[kind]) {
  26965. this._vertexBuffers[kind].dispose();
  26966. delete this._vertexBuffers[kind];
  26967. }
  26968. };
  26969. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26970. var kind = buffer.getKind();
  26971. if (this._vertexBuffers[kind]) {
  26972. this._vertexBuffers[kind].dispose();
  26973. }
  26974. this._vertexBuffers[kind] = buffer;
  26975. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26976. var data = buffer.getData();
  26977. var stride = buffer.getStrideSize();
  26978. this._totalVertices = data.length / stride;
  26979. this.updateExtend(data, stride);
  26980. this._resetPointsArrayCache();
  26981. var meshes = this._meshes;
  26982. var numOfMeshes = meshes.length;
  26983. for (var index = 0; index < numOfMeshes; index++) {
  26984. var mesh = meshes[index];
  26985. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26986. mesh._createGlobalSubMesh();
  26987. mesh.computeWorldMatrix(true);
  26988. }
  26989. }
  26990. this.notifyUpdate(kind);
  26991. if (this._vertexArrayObjects) {
  26992. this._disposeVertexArrayObjects();
  26993. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26994. }
  26995. };
  26996. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26997. var vertexBuffer = this.getVertexBuffer(kind);
  26998. if (!vertexBuffer) {
  26999. return;
  27000. }
  27001. vertexBuffer.updateDirectly(data, offset);
  27002. this.notifyUpdate(kind);
  27003. };
  27004. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27005. var vertexBuffer = this.getVertexBuffer(kind);
  27006. if (!vertexBuffer) {
  27007. return;
  27008. }
  27009. vertexBuffer.update(data);
  27010. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27011. var stride = vertexBuffer.getStrideSize();
  27012. this._totalVertices = data.length / stride;
  27013. this.updateBoundingInfo(updateExtends, data);
  27014. }
  27015. this.notifyUpdate(kind);
  27016. };
  27017. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27018. if (updateExtends) {
  27019. this.updateExtend(data);
  27020. }
  27021. var meshes = this._meshes;
  27022. var numOfMeshes = meshes.length;
  27023. this._resetPointsArrayCache();
  27024. for (var index = 0; index < numOfMeshes; index++) {
  27025. var mesh = meshes[index];
  27026. if (updateExtends) {
  27027. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27028. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27029. var subMesh = mesh.subMeshes[subIndex];
  27030. subMesh.refreshBoundingInfo();
  27031. }
  27032. }
  27033. }
  27034. };
  27035. Geometry.prototype._bind = function (effect, indexToBind) {
  27036. if (indexToBind === void 0) { indexToBind = undefined; }
  27037. if (indexToBind === undefined) {
  27038. indexToBind = this._indexBuffer;
  27039. }
  27040. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27041. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27042. return;
  27043. }
  27044. // Using VAO
  27045. if (!this._vertexArrayObjects[effect.key]) {
  27046. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27047. }
  27048. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27049. };
  27050. Geometry.prototype.getTotalVertices = function () {
  27051. if (!this.isReady()) {
  27052. return 0;
  27053. }
  27054. return this._totalVertices;
  27055. };
  27056. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27057. var vertexBuffer = this.getVertexBuffer(kind);
  27058. if (!vertexBuffer) {
  27059. return null;
  27060. }
  27061. var orig = vertexBuffer.getData();
  27062. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27063. return orig;
  27064. }
  27065. else {
  27066. var len = orig.length;
  27067. var copy = [];
  27068. for (var i = 0; i < len; i++) {
  27069. copy.push(orig[i]);
  27070. }
  27071. return copy;
  27072. }
  27073. };
  27074. Geometry.prototype.getVertexBuffer = function (kind) {
  27075. if (!this.isReady()) {
  27076. return null;
  27077. }
  27078. return this._vertexBuffers[kind];
  27079. };
  27080. Geometry.prototype.getVertexBuffers = function () {
  27081. if (!this.isReady()) {
  27082. return null;
  27083. }
  27084. return this._vertexBuffers;
  27085. };
  27086. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27087. if (!this._vertexBuffers) {
  27088. if (this._delayInfo) {
  27089. return this._delayInfo.indexOf(kind) !== -1;
  27090. }
  27091. return false;
  27092. }
  27093. return this._vertexBuffers[kind] !== undefined;
  27094. };
  27095. Geometry.prototype.getVerticesDataKinds = function () {
  27096. var result = [];
  27097. var kind;
  27098. if (!this._vertexBuffers && this._delayInfo) {
  27099. for (kind in this._delayInfo) {
  27100. result.push(kind);
  27101. }
  27102. }
  27103. else {
  27104. for (kind in this._vertexBuffers) {
  27105. result.push(kind);
  27106. }
  27107. }
  27108. return result;
  27109. };
  27110. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27111. if (this._indexBuffer) {
  27112. this._engine._releaseBuffer(this._indexBuffer);
  27113. }
  27114. this._disposeVertexArrayObjects();
  27115. this._indices = indices;
  27116. if (this._meshes.length !== 0 && this._indices) {
  27117. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27118. }
  27119. if (totalVertices !== undefined) {
  27120. this._totalVertices = totalVertices;
  27121. }
  27122. var meshes = this._meshes;
  27123. var numOfMeshes = meshes.length;
  27124. for (var index = 0; index < numOfMeshes; index++) {
  27125. meshes[index]._createGlobalSubMesh();
  27126. }
  27127. this.notifyUpdate();
  27128. };
  27129. Geometry.prototype.getTotalIndices = function () {
  27130. if (!this.isReady()) {
  27131. return 0;
  27132. }
  27133. return this._indices.length;
  27134. };
  27135. Geometry.prototype.getIndices = function (copyWhenShared) {
  27136. if (!this.isReady()) {
  27137. return null;
  27138. }
  27139. var orig = this._indices;
  27140. if (!copyWhenShared || this._meshes.length === 1) {
  27141. return orig;
  27142. }
  27143. else {
  27144. var len = orig.length;
  27145. var copy = [];
  27146. for (var i = 0; i < len; i++) {
  27147. copy.push(orig[i]);
  27148. }
  27149. return copy;
  27150. }
  27151. };
  27152. Geometry.prototype.getIndexBuffer = function () {
  27153. if (!this.isReady()) {
  27154. return null;
  27155. }
  27156. return this._indexBuffer;
  27157. };
  27158. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27159. if (!effect || !this._vertexArrayObjects) {
  27160. return;
  27161. }
  27162. if (this._vertexArrayObjects[effect.key]) {
  27163. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27164. delete this._vertexArrayObjects[effect.key];
  27165. }
  27166. };
  27167. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27168. var meshes = this._meshes;
  27169. var index = meshes.indexOf(mesh);
  27170. if (index === -1) {
  27171. return;
  27172. }
  27173. meshes.splice(index, 1);
  27174. mesh._geometry = null;
  27175. if (meshes.length === 0 && shouldDispose) {
  27176. this.dispose();
  27177. }
  27178. };
  27179. Geometry.prototype.applyToMesh = function (mesh) {
  27180. if (mesh._geometry === this) {
  27181. return;
  27182. }
  27183. var previousGeometry = mesh._geometry;
  27184. if (previousGeometry) {
  27185. previousGeometry.releaseForMesh(mesh);
  27186. }
  27187. var meshes = this._meshes;
  27188. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27189. mesh._geometry = this;
  27190. this._scene.pushGeometry(this);
  27191. meshes.push(mesh);
  27192. if (this.isReady()) {
  27193. this._applyToMesh(mesh);
  27194. }
  27195. else {
  27196. mesh._boundingInfo = this._boundingInfo;
  27197. }
  27198. };
  27199. Geometry.prototype.updateExtend = function (data, stride) {
  27200. if (data === void 0) { data = null; }
  27201. if (!data) {
  27202. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27203. }
  27204. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27205. };
  27206. Geometry.prototype._applyToMesh = function (mesh) {
  27207. var numOfMeshes = this._meshes.length;
  27208. // vertexBuffers
  27209. for (var kind in this._vertexBuffers) {
  27210. if (numOfMeshes === 1) {
  27211. this._vertexBuffers[kind].create();
  27212. }
  27213. var buffer = this._vertexBuffers[kind].getBuffer();
  27214. if (buffer)
  27215. buffer.references = numOfMeshes;
  27216. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27217. if (!this._extend) {
  27218. this.updateExtend(this._vertexBuffers[kind].getData());
  27219. }
  27220. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27221. mesh._createGlobalSubMesh();
  27222. //bounding info was just created again, world matrix should be applied again.
  27223. mesh._updateBoundingInfo();
  27224. }
  27225. }
  27226. // indexBuffer
  27227. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27228. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27229. }
  27230. if (this._indexBuffer) {
  27231. this._indexBuffer.references = numOfMeshes;
  27232. }
  27233. };
  27234. Geometry.prototype.notifyUpdate = function (kind) {
  27235. if (this.onGeometryUpdated) {
  27236. this.onGeometryUpdated(this, kind);
  27237. }
  27238. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27239. var mesh = _a[_i];
  27240. mesh._markSubMeshesAsAttributesDirty();
  27241. }
  27242. };
  27243. Geometry.prototype.load = function (scene, onLoaded) {
  27244. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27245. return;
  27246. }
  27247. if (this.isReady()) {
  27248. if (onLoaded) {
  27249. onLoaded();
  27250. }
  27251. return;
  27252. }
  27253. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27254. this._queueLoad(scene, onLoaded);
  27255. };
  27256. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27257. var _this = this;
  27258. scene._addPendingData(this);
  27259. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27260. _this._delayLoadingFunction(JSON.parse(data), _this);
  27261. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27262. _this._delayInfo = [];
  27263. scene._removePendingData(_this);
  27264. var meshes = _this._meshes;
  27265. var numOfMeshes = meshes.length;
  27266. for (var index = 0; index < numOfMeshes; index++) {
  27267. _this._applyToMesh(meshes[index]);
  27268. }
  27269. if (onLoaded) {
  27270. onLoaded();
  27271. }
  27272. }, function () { }, scene.database);
  27273. };
  27274. /**
  27275. * Invert the geometry to move from a right handed system to a left handed one.
  27276. */
  27277. Geometry.prototype.toLeftHanded = function () {
  27278. // Flip faces
  27279. var tIndices = this.getIndices(false);
  27280. if (tIndices != null && tIndices.length > 0) {
  27281. for (var i = 0; i < tIndices.length; i += 3) {
  27282. var tTemp = tIndices[i + 0];
  27283. tIndices[i + 0] = tIndices[i + 2];
  27284. tIndices[i + 2] = tTemp;
  27285. }
  27286. this.setIndices(tIndices);
  27287. }
  27288. // Negate position.z
  27289. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27290. if (tPositions != null && tPositions.length > 0) {
  27291. for (var i = 0; i < tPositions.length; i += 3) {
  27292. tPositions[i + 2] = -tPositions[i + 2];
  27293. }
  27294. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27295. }
  27296. // Negate normal.z
  27297. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27298. if (tNormals != null && tNormals.length > 0) {
  27299. for (var i = 0; i < tNormals.length; i += 3) {
  27300. tNormals[i + 2] = -tNormals[i + 2];
  27301. }
  27302. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27303. }
  27304. };
  27305. // Cache
  27306. Geometry.prototype._resetPointsArrayCache = function () {
  27307. this._positions = null;
  27308. };
  27309. Geometry.prototype._generatePointsArray = function () {
  27310. if (this._positions)
  27311. return true;
  27312. this._positions = [];
  27313. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27314. if (!data) {
  27315. return false;
  27316. }
  27317. for (var index = 0; index < data.length; index += 3) {
  27318. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27319. }
  27320. return true;
  27321. };
  27322. Geometry.prototype.isDisposed = function () {
  27323. return this._isDisposed;
  27324. };
  27325. Geometry.prototype._disposeVertexArrayObjects = function () {
  27326. if (this._vertexArrayObjects) {
  27327. for (var kind in this._vertexArrayObjects) {
  27328. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27329. }
  27330. this._vertexArrayObjects = {};
  27331. }
  27332. };
  27333. Geometry.prototype.dispose = function () {
  27334. var meshes = this._meshes;
  27335. var numOfMeshes = meshes.length;
  27336. var index;
  27337. for (index = 0; index < numOfMeshes; index++) {
  27338. this.releaseForMesh(meshes[index]);
  27339. }
  27340. this._meshes = [];
  27341. this._disposeVertexArrayObjects();
  27342. for (var kind in this._vertexBuffers) {
  27343. this._vertexBuffers[kind].dispose();
  27344. }
  27345. this._vertexBuffers = {};
  27346. this._totalVertices = 0;
  27347. if (this._indexBuffer) {
  27348. this._engine._releaseBuffer(this._indexBuffer);
  27349. }
  27350. this._indexBuffer = null;
  27351. this._indices = [];
  27352. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27353. this.delayLoadingFile = null;
  27354. this._delayLoadingFunction = null;
  27355. this._delayInfo = [];
  27356. this._boundingInfo = null;
  27357. this._scene.removeGeometry(this);
  27358. this._isDisposed = true;
  27359. };
  27360. Geometry.prototype.copy = function (id) {
  27361. var vertexData = new BABYLON.VertexData();
  27362. vertexData.indices = [];
  27363. var indices = this.getIndices();
  27364. for (var index = 0; index < indices.length; index++) {
  27365. vertexData.indices.push(indices[index]);
  27366. }
  27367. var updatable = false;
  27368. var stopChecking = false;
  27369. var kind;
  27370. for (kind in this._vertexBuffers) {
  27371. // using slice() to make a copy of the array and not just reference it
  27372. var data = this.getVerticesData(kind);
  27373. if (data instanceof Float32Array) {
  27374. vertexData.set(new Float32Array(data), kind);
  27375. }
  27376. else {
  27377. vertexData.set(data.slice(0), kind);
  27378. }
  27379. if (!stopChecking) {
  27380. updatable = this.getVertexBuffer(kind).isUpdatable();
  27381. stopChecking = !updatable;
  27382. }
  27383. }
  27384. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27385. geometry.delayLoadState = this.delayLoadState;
  27386. geometry.delayLoadingFile = this.delayLoadingFile;
  27387. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27388. for (kind in this._delayInfo) {
  27389. geometry._delayInfo = geometry._delayInfo || [];
  27390. geometry._delayInfo.push(kind);
  27391. }
  27392. // Bounding info
  27393. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27394. return geometry;
  27395. };
  27396. Geometry.prototype.serialize = function () {
  27397. var serializationObject = {};
  27398. serializationObject.id = this.id;
  27399. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27400. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27401. }
  27402. return serializationObject;
  27403. };
  27404. Geometry.prototype.toNumberArray = function (origin) {
  27405. if (Array.isArray(origin)) {
  27406. return origin;
  27407. }
  27408. else {
  27409. return Array.prototype.slice.call(origin);
  27410. }
  27411. };
  27412. Geometry.prototype.serializeVerticeData = function () {
  27413. var serializationObject = this.serialize();
  27414. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27415. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27416. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27417. serializationObject.positions._updatable = true;
  27418. }
  27419. }
  27420. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27421. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27422. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27423. serializationObject.normals._updatable = true;
  27424. }
  27425. }
  27426. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27427. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27428. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27429. serializationObject.uvs._updatable = true;
  27430. }
  27431. }
  27432. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27433. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27434. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27435. serializationObject.uv2s._updatable = true;
  27436. }
  27437. }
  27438. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27439. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27440. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27441. serializationObject.uv3s._updatable = true;
  27442. }
  27443. }
  27444. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27445. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27446. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27447. serializationObject.uv4s._updatable = true;
  27448. }
  27449. }
  27450. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27451. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27452. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27453. serializationObject.uv5s._updatable = true;
  27454. }
  27455. }
  27456. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27457. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27458. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27459. serializationObject.uv6s._updatable = true;
  27460. }
  27461. }
  27462. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27463. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27464. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27465. serializationObject.colors._updatable = true;
  27466. }
  27467. }
  27468. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27469. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27470. serializationObject.matricesIndices._isExpanded = true;
  27471. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27472. serializationObject.matricesIndices._updatable = true;
  27473. }
  27474. }
  27475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27476. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27477. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27478. serializationObject.matricesWeights._updatable = true;
  27479. }
  27480. }
  27481. serializationObject.indices = this.toNumberArray(this.getIndices());
  27482. return serializationObject;
  27483. };
  27484. // Statics
  27485. Geometry.ExtractFromMesh = function (mesh, id) {
  27486. var geometry = mesh._geometry;
  27487. if (!geometry) {
  27488. return null;
  27489. }
  27490. return geometry.copy(id);
  27491. };
  27492. /**
  27493. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27494. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27495. * Be aware Math.random() could cause collisions, but:
  27496. * "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"
  27497. */
  27498. Geometry.RandomId = function () {
  27499. return BABYLON.Tools.RandomId();
  27500. };
  27501. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27502. var scene = mesh.getScene();
  27503. // Geometry
  27504. var geometryId = parsedGeometry.geometryId;
  27505. if (geometryId) {
  27506. var geometry = scene.getGeometryByID(geometryId);
  27507. if (geometry) {
  27508. geometry.applyToMesh(mesh);
  27509. }
  27510. }
  27511. else if (parsedGeometry instanceof ArrayBuffer) {
  27512. var binaryInfo = mesh._binaryInfo;
  27513. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27514. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27515. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27516. }
  27517. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27518. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27519. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27520. }
  27521. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27522. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27523. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27524. }
  27525. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27526. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27527. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27528. }
  27529. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27530. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27531. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27532. }
  27533. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27534. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27535. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27536. }
  27537. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27538. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27539. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27540. }
  27541. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27542. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27543. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27544. }
  27545. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27546. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27547. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27548. }
  27549. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27550. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27552. }
  27553. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27554. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27555. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27556. }
  27557. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27558. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27559. mesh.setIndices(indicesData);
  27560. }
  27561. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27562. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27563. mesh.subMeshes = [];
  27564. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27565. var materialIndex = subMeshesData[(i * 5) + 0];
  27566. var verticesStart = subMeshesData[(i * 5) + 1];
  27567. var verticesCount = subMeshesData[(i * 5) + 2];
  27568. var indexStart = subMeshesData[(i * 5) + 3];
  27569. var indexCount = subMeshesData[(i * 5) + 4];
  27570. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27571. }
  27572. }
  27573. }
  27574. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27575. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27576. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27577. if (parsedGeometry.uvs) {
  27578. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27579. }
  27580. if (parsedGeometry.uvs2) {
  27581. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27582. }
  27583. if (parsedGeometry.uvs3) {
  27584. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27585. }
  27586. if (parsedGeometry.uvs4) {
  27587. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27588. }
  27589. if (parsedGeometry.uvs5) {
  27590. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27591. }
  27592. if (parsedGeometry.uvs6) {
  27593. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27594. }
  27595. if (parsedGeometry.colors) {
  27596. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27597. }
  27598. if (parsedGeometry.matricesIndices) {
  27599. if (!parsedGeometry.matricesIndices._isExpanded) {
  27600. var floatIndices = [];
  27601. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27602. var matricesIndex = parsedGeometry.matricesIndices[i];
  27603. floatIndices.push(matricesIndex & 0x000000FF);
  27604. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27605. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27606. floatIndices.push(matricesIndex >> 24);
  27607. }
  27608. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27609. }
  27610. else {
  27611. delete parsedGeometry.matricesIndices._isExpanded;
  27612. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27613. }
  27614. }
  27615. if (parsedGeometry.matricesIndicesExtra) {
  27616. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27617. var floatIndices = [];
  27618. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27619. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27620. floatIndices.push(matricesIndex & 0x000000FF);
  27621. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27622. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27623. floatIndices.push(matricesIndex >> 24);
  27624. }
  27625. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27626. }
  27627. else {
  27628. delete parsedGeometry.matricesIndices._isExpanded;
  27629. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27630. }
  27631. }
  27632. if (parsedGeometry.matricesWeights) {
  27633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27634. }
  27635. if (parsedGeometry.matricesWeightsExtra) {
  27636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27637. }
  27638. mesh.setIndices(parsedGeometry.indices);
  27639. }
  27640. // SubMeshes
  27641. if (parsedGeometry.subMeshes) {
  27642. mesh.subMeshes = [];
  27643. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27644. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27645. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27646. }
  27647. }
  27648. // Flat shading
  27649. if (mesh._shouldGenerateFlatShading) {
  27650. mesh.convertToFlatShadedMesh();
  27651. delete mesh._shouldGenerateFlatShading;
  27652. }
  27653. // Update
  27654. mesh.computeWorldMatrix(true);
  27655. // Octree
  27656. if (scene['_selectionOctree']) {
  27657. scene['_selectionOctree'].addMesh(mesh);
  27658. }
  27659. };
  27660. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27661. if (scene.getGeometryByID(parsedVertexData.id)) {
  27662. return null; // null since geometry could be something else than a box...
  27663. }
  27664. var geometry = new Geometry(parsedVertexData.id, scene);
  27665. if (BABYLON.Tags) {
  27666. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27667. }
  27668. if (parsedVertexData.delayLoadingFile) {
  27669. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27670. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27671. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27672. geometry._delayInfo = [];
  27673. if (parsedVertexData.hasUVs) {
  27674. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27675. }
  27676. if (parsedVertexData.hasUVs2) {
  27677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27678. }
  27679. if (parsedVertexData.hasUVs3) {
  27680. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27681. }
  27682. if (parsedVertexData.hasUVs4) {
  27683. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27684. }
  27685. if (parsedVertexData.hasUVs5) {
  27686. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27687. }
  27688. if (parsedVertexData.hasUVs6) {
  27689. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27690. }
  27691. if (parsedVertexData.hasColors) {
  27692. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27693. }
  27694. if (parsedVertexData.hasMatricesIndices) {
  27695. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27696. }
  27697. if (parsedVertexData.hasMatricesWeights) {
  27698. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27699. }
  27700. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27701. }
  27702. else {
  27703. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27704. }
  27705. scene.pushGeometry(geometry, true);
  27706. return geometry;
  27707. };
  27708. return Geometry;
  27709. }());
  27710. BABYLON.Geometry = Geometry;
  27711. /////// Primitives //////////////////////////////////////////////
  27712. (function (Geometry) {
  27713. var Primitives;
  27714. (function (Primitives) {
  27715. /// Abstract class
  27716. var _Primitive = (function (_super) {
  27717. __extends(_Primitive, _super);
  27718. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27719. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27720. _this._canBeRegenerated = _canBeRegenerated;
  27721. _this._beingRegenerated = true;
  27722. _this.regenerate();
  27723. _this._beingRegenerated = false;
  27724. return _this;
  27725. }
  27726. _Primitive.prototype.canBeRegenerated = function () {
  27727. return this._canBeRegenerated;
  27728. };
  27729. _Primitive.prototype.regenerate = function () {
  27730. if (!this._canBeRegenerated) {
  27731. return;
  27732. }
  27733. this._beingRegenerated = true;
  27734. this.setAllVerticesData(this._regenerateVertexData(), false);
  27735. this._beingRegenerated = false;
  27736. };
  27737. _Primitive.prototype.asNewGeometry = function (id) {
  27738. return _super.prototype.copy.call(this, id);
  27739. };
  27740. // overrides
  27741. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27742. if (!this._beingRegenerated) {
  27743. return;
  27744. }
  27745. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27746. };
  27747. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27748. if (!this._beingRegenerated) {
  27749. return;
  27750. }
  27751. _super.prototype.setVerticesData.call(this, kind, data, false);
  27752. };
  27753. // to override
  27754. // protected
  27755. _Primitive.prototype._regenerateVertexData = function () {
  27756. throw new Error("Abstract method");
  27757. };
  27758. _Primitive.prototype.copy = function (id) {
  27759. throw new Error("Must be overriden in sub-classes.");
  27760. };
  27761. _Primitive.prototype.serialize = function () {
  27762. var serializationObject = _super.prototype.serialize.call(this);
  27763. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27764. return serializationObject;
  27765. };
  27766. return _Primitive;
  27767. }(Geometry));
  27768. Primitives._Primitive = _Primitive;
  27769. var Ribbon = (function (_super) {
  27770. __extends(Ribbon, _super);
  27771. // Members
  27772. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27773. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27774. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27775. _this.pathArray = pathArray;
  27776. _this.closeArray = closeArray;
  27777. _this.closePath = closePath;
  27778. _this.offset = offset;
  27779. _this.side = side;
  27780. return _this;
  27781. }
  27782. Ribbon.prototype._regenerateVertexData = function () {
  27783. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27784. };
  27785. Ribbon.prototype.copy = function (id) {
  27786. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27787. };
  27788. return Ribbon;
  27789. }(_Primitive));
  27790. Primitives.Ribbon = Ribbon;
  27791. var Box = (function (_super) {
  27792. __extends(Box, _super);
  27793. // Members
  27794. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27797. _this.size = size;
  27798. _this.side = side;
  27799. return _this;
  27800. }
  27801. Box.prototype._regenerateVertexData = function () {
  27802. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27803. };
  27804. Box.prototype.copy = function (id) {
  27805. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27806. };
  27807. Box.prototype.serialize = function () {
  27808. var serializationObject = _super.prototype.serialize.call(this);
  27809. serializationObject.size = this.size;
  27810. return serializationObject;
  27811. };
  27812. Box.Parse = function (parsedBox, scene) {
  27813. if (scene.getGeometryByID(parsedBox.id)) {
  27814. return null; // null since geometry could be something else than a box...
  27815. }
  27816. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27817. if (BABYLON.Tags) {
  27818. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27819. }
  27820. scene.pushGeometry(box, true);
  27821. return box;
  27822. };
  27823. return Box;
  27824. }(_Primitive));
  27825. Primitives.Box = Box;
  27826. var Sphere = (function (_super) {
  27827. __extends(Sphere, _super);
  27828. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27829. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27830. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27831. _this.segments = segments;
  27832. _this.diameter = diameter;
  27833. _this.side = side;
  27834. return _this;
  27835. }
  27836. Sphere.prototype._regenerateVertexData = function () {
  27837. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27838. };
  27839. Sphere.prototype.copy = function (id) {
  27840. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27841. };
  27842. Sphere.prototype.serialize = function () {
  27843. var serializationObject = _super.prototype.serialize.call(this);
  27844. serializationObject.segments = this.segments;
  27845. serializationObject.diameter = this.diameter;
  27846. return serializationObject;
  27847. };
  27848. Sphere.Parse = function (parsedSphere, scene) {
  27849. if (scene.getGeometryByID(parsedSphere.id)) {
  27850. return null; // null since geometry could be something else than a sphere...
  27851. }
  27852. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27853. if (BABYLON.Tags) {
  27854. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27855. }
  27856. scene.pushGeometry(sphere, true);
  27857. return sphere;
  27858. };
  27859. return Sphere;
  27860. }(_Primitive));
  27861. Primitives.Sphere = Sphere;
  27862. var Disc = (function (_super) {
  27863. __extends(Disc, _super);
  27864. // Members
  27865. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27866. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27867. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27868. _this.radius = radius;
  27869. _this.tessellation = tessellation;
  27870. _this.side = side;
  27871. return _this;
  27872. }
  27873. Disc.prototype._regenerateVertexData = function () {
  27874. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27875. };
  27876. Disc.prototype.copy = function (id) {
  27877. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27878. };
  27879. return Disc;
  27880. }(_Primitive));
  27881. Primitives.Disc = Disc;
  27882. var Cylinder = (function (_super) {
  27883. __extends(Cylinder, _super);
  27884. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27885. if (subdivisions === void 0) { subdivisions = 1; }
  27886. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27887. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27888. _this.height = height;
  27889. _this.diameterTop = diameterTop;
  27890. _this.diameterBottom = diameterBottom;
  27891. _this.tessellation = tessellation;
  27892. _this.subdivisions = subdivisions;
  27893. _this.side = side;
  27894. return _this;
  27895. }
  27896. Cylinder.prototype._regenerateVertexData = function () {
  27897. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27898. };
  27899. Cylinder.prototype.copy = function (id) {
  27900. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27901. };
  27902. Cylinder.prototype.serialize = function () {
  27903. var serializationObject = _super.prototype.serialize.call(this);
  27904. serializationObject.height = this.height;
  27905. serializationObject.diameterTop = this.diameterTop;
  27906. serializationObject.diameterBottom = this.diameterBottom;
  27907. serializationObject.tessellation = this.tessellation;
  27908. return serializationObject;
  27909. };
  27910. Cylinder.Parse = function (parsedCylinder, scene) {
  27911. if (scene.getGeometryByID(parsedCylinder.id)) {
  27912. return null; // null since geometry could be something else than a cylinder...
  27913. }
  27914. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27915. if (BABYLON.Tags) {
  27916. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27917. }
  27918. scene.pushGeometry(cylinder, true);
  27919. return cylinder;
  27920. };
  27921. return Cylinder;
  27922. }(_Primitive));
  27923. Primitives.Cylinder = Cylinder;
  27924. var Torus = (function (_super) {
  27925. __extends(Torus, _super);
  27926. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27928. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27929. _this.diameter = diameter;
  27930. _this.thickness = thickness;
  27931. _this.tessellation = tessellation;
  27932. _this.side = side;
  27933. return _this;
  27934. }
  27935. Torus.prototype._regenerateVertexData = function () {
  27936. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27937. };
  27938. Torus.prototype.copy = function (id) {
  27939. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27940. };
  27941. Torus.prototype.serialize = function () {
  27942. var serializationObject = _super.prototype.serialize.call(this);
  27943. serializationObject.diameter = this.diameter;
  27944. serializationObject.thickness = this.thickness;
  27945. serializationObject.tessellation = this.tessellation;
  27946. return serializationObject;
  27947. };
  27948. Torus.Parse = function (parsedTorus, scene) {
  27949. if (scene.getGeometryByID(parsedTorus.id)) {
  27950. return null; // null since geometry could be something else than a torus...
  27951. }
  27952. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27953. if (BABYLON.Tags) {
  27954. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27955. }
  27956. scene.pushGeometry(torus, true);
  27957. return torus;
  27958. };
  27959. return Torus;
  27960. }(_Primitive));
  27961. Primitives.Torus = Torus;
  27962. var Ground = (function (_super) {
  27963. __extends(Ground, _super);
  27964. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27965. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27966. _this.width = width;
  27967. _this.height = height;
  27968. _this.subdivisions = subdivisions;
  27969. return _this;
  27970. }
  27971. Ground.prototype._regenerateVertexData = function () {
  27972. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27973. };
  27974. Ground.prototype.copy = function (id) {
  27975. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27976. };
  27977. Ground.prototype.serialize = function () {
  27978. var serializationObject = _super.prototype.serialize.call(this);
  27979. serializationObject.width = this.width;
  27980. serializationObject.height = this.height;
  27981. serializationObject.subdivisions = this.subdivisions;
  27982. return serializationObject;
  27983. };
  27984. Ground.Parse = function (parsedGround, scene) {
  27985. if (scene.getGeometryByID(parsedGround.id)) {
  27986. return null; // null since geometry could be something else than a ground...
  27987. }
  27988. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27989. if (BABYLON.Tags) {
  27990. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27991. }
  27992. scene.pushGeometry(ground, true);
  27993. return ground;
  27994. };
  27995. return Ground;
  27996. }(_Primitive));
  27997. Primitives.Ground = Ground;
  27998. var TiledGround = (function (_super) {
  27999. __extends(TiledGround, _super);
  28000. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28001. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28002. _this.xmin = xmin;
  28003. _this.zmin = zmin;
  28004. _this.xmax = xmax;
  28005. _this.zmax = zmax;
  28006. _this.subdivisions = subdivisions;
  28007. _this.precision = precision;
  28008. return _this;
  28009. }
  28010. TiledGround.prototype._regenerateVertexData = function () {
  28011. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28012. };
  28013. TiledGround.prototype.copy = function (id) {
  28014. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28015. };
  28016. return TiledGround;
  28017. }(_Primitive));
  28018. Primitives.TiledGround = TiledGround;
  28019. var Plane = (function (_super) {
  28020. __extends(Plane, _super);
  28021. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28024. _this.size = size;
  28025. _this.side = side;
  28026. return _this;
  28027. }
  28028. Plane.prototype._regenerateVertexData = function () {
  28029. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28030. };
  28031. Plane.prototype.copy = function (id) {
  28032. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28033. };
  28034. Plane.prototype.serialize = function () {
  28035. var serializationObject = _super.prototype.serialize.call(this);
  28036. serializationObject.size = this.size;
  28037. return serializationObject;
  28038. };
  28039. Plane.Parse = function (parsedPlane, scene) {
  28040. if (scene.getGeometryByID(parsedPlane.id)) {
  28041. return null; // null since geometry could be something else than a ground...
  28042. }
  28043. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28044. if (BABYLON.Tags) {
  28045. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28046. }
  28047. scene.pushGeometry(plane, true);
  28048. return plane;
  28049. };
  28050. return Plane;
  28051. }(_Primitive));
  28052. Primitives.Plane = Plane;
  28053. var TorusKnot = (function (_super) {
  28054. __extends(TorusKnot, _super);
  28055. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28056. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28057. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28058. _this.radius = radius;
  28059. _this.tube = tube;
  28060. _this.radialSegments = radialSegments;
  28061. _this.tubularSegments = tubularSegments;
  28062. _this.p = p;
  28063. _this.q = q;
  28064. _this.side = side;
  28065. return _this;
  28066. }
  28067. TorusKnot.prototype._regenerateVertexData = function () {
  28068. 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 });
  28069. };
  28070. TorusKnot.prototype.copy = function (id) {
  28071. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28072. };
  28073. TorusKnot.prototype.serialize = function () {
  28074. var serializationObject = _super.prototype.serialize.call(this);
  28075. serializationObject.radius = this.radius;
  28076. serializationObject.tube = this.tube;
  28077. serializationObject.radialSegments = this.radialSegments;
  28078. serializationObject.tubularSegments = this.tubularSegments;
  28079. serializationObject.p = this.p;
  28080. serializationObject.q = this.q;
  28081. return serializationObject;
  28082. };
  28083. ;
  28084. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28085. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28086. return null; // null since geometry could be something else than a ground...
  28087. }
  28088. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28089. if (BABYLON.Tags) {
  28090. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28091. }
  28092. scene.pushGeometry(torusKnot, true);
  28093. return torusKnot;
  28094. };
  28095. return TorusKnot;
  28096. }(_Primitive));
  28097. Primitives.TorusKnot = TorusKnot;
  28098. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28099. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28100. })(BABYLON || (BABYLON = {}));
  28101. //# sourceMappingURL=babylon.geometry.js.map
  28102. var BABYLON;
  28103. (function (BABYLON) {
  28104. var PostProcessManager = (function () {
  28105. function PostProcessManager(scene) {
  28106. this._vertexBuffers = {};
  28107. this._scene = scene;
  28108. }
  28109. PostProcessManager.prototype._prepareBuffers = function () {
  28110. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28111. return;
  28112. }
  28113. // VBO
  28114. var vertices = [];
  28115. vertices.push(1, 1);
  28116. vertices.push(-1, 1);
  28117. vertices.push(-1, -1);
  28118. vertices.push(1, -1);
  28119. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28120. // Indices
  28121. var indices = [];
  28122. indices.push(0);
  28123. indices.push(1);
  28124. indices.push(2);
  28125. indices.push(0);
  28126. indices.push(2);
  28127. indices.push(3);
  28128. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28129. };
  28130. // Methods
  28131. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28132. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28133. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28134. return false;
  28135. }
  28136. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28137. return true;
  28138. };
  28139. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28140. var engine = this._scene.getEngine();
  28141. for (var index = 0; index < postProcesses.length; index++) {
  28142. if (index < postProcesses.length - 1) {
  28143. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28144. }
  28145. else {
  28146. if (targetTexture) {
  28147. engine.bindFramebuffer(targetTexture);
  28148. }
  28149. else {
  28150. engine.restoreDefaultFramebuffer();
  28151. }
  28152. }
  28153. var pp = postProcesses[index];
  28154. var effect = pp.apply();
  28155. if (effect) {
  28156. pp.onBeforeRenderObservable.notifyObservers(effect);
  28157. // VBOs
  28158. this._prepareBuffers();
  28159. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28160. // Draw order
  28161. engine.draw(true, 0, 6);
  28162. pp.onAfterRenderObservable.notifyObservers(effect);
  28163. }
  28164. }
  28165. // Restore depth buffer
  28166. engine.setDepthBuffer(true);
  28167. engine.setDepthWrite(true);
  28168. };
  28169. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28170. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28171. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28172. return;
  28173. }
  28174. var engine = this._scene.getEngine();
  28175. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28176. if (index < len - 1) {
  28177. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28178. }
  28179. else {
  28180. if (targetTexture) {
  28181. engine.bindFramebuffer(targetTexture, faceIndex);
  28182. }
  28183. else {
  28184. engine.restoreDefaultFramebuffer();
  28185. }
  28186. }
  28187. if (doNotPresent) {
  28188. break;
  28189. }
  28190. var pp = postProcesses[index];
  28191. var effect = pp.apply();
  28192. if (effect) {
  28193. pp.onBeforeRenderObservable.notifyObservers(effect);
  28194. // VBOs
  28195. this._prepareBuffers();
  28196. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28197. // Draw order
  28198. engine.draw(true, 0, 6);
  28199. pp.onAfterRenderObservable.notifyObservers(effect);
  28200. }
  28201. }
  28202. // Restore states
  28203. engine.setDepthBuffer(true);
  28204. engine.setDepthWrite(true);
  28205. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28206. };
  28207. PostProcessManager.prototype.dispose = function () {
  28208. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28209. if (buffer) {
  28210. buffer.dispose();
  28211. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28212. }
  28213. if (this._indexBuffer) {
  28214. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28215. this._indexBuffer = null;
  28216. }
  28217. };
  28218. return PostProcessManager;
  28219. }());
  28220. BABYLON.PostProcessManager = PostProcessManager;
  28221. })(BABYLON || (BABYLON = {}));
  28222. //# sourceMappingURL=babylon.postProcessManager.js.map
  28223. var BABYLON;
  28224. (function (BABYLON) {
  28225. var StandardMaterialDefines = (function (_super) {
  28226. __extends(StandardMaterialDefines, _super);
  28227. function StandardMaterialDefines() {
  28228. var _this = _super.call(this) || this;
  28229. _this.DIFFUSE = false;
  28230. _this.AMBIENT = false;
  28231. _this.OPACITY = false;
  28232. _this.OPACITYRGB = false;
  28233. _this.REFLECTION = false;
  28234. _this.EMISSIVE = false;
  28235. _this.SPECULAR = false;
  28236. _this.BUMP = false;
  28237. _this.PARALLAX = false;
  28238. _this.PARALLAXOCCLUSION = false;
  28239. _this.SPECULAROVERALPHA = false;
  28240. _this.CLIPPLANE = false;
  28241. _this.ALPHATEST = false;
  28242. _this.ALPHAFROMDIFFUSE = false;
  28243. _this.POINTSIZE = false;
  28244. _this.FOG = false;
  28245. _this.SPECULARTERM = false;
  28246. _this.DIFFUSEFRESNEL = false;
  28247. _this.OPACITYFRESNEL = false;
  28248. _this.REFLECTIONFRESNEL = false;
  28249. _this.REFRACTIONFRESNEL = false;
  28250. _this.EMISSIVEFRESNEL = false;
  28251. _this.FRESNEL = false;
  28252. _this.NORMAL = false;
  28253. _this.UV1 = false;
  28254. _this.UV2 = false;
  28255. _this.VERTEXCOLOR = false;
  28256. _this.VERTEXALPHA = false;
  28257. _this.NUM_BONE_INFLUENCERS = 0;
  28258. _this.BonesPerMesh = 0;
  28259. _this.INSTANCES = false;
  28260. _this.GLOSSINESS = false;
  28261. _this.ROUGHNESS = false;
  28262. _this.EMISSIVEASILLUMINATION = false;
  28263. _this.LINKEMISSIVEWITHDIFFUSE = false;
  28264. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  28265. _this.LIGHTMAP = false;
  28266. _this.USELIGHTMAPASSHADOWMAP = false;
  28267. _this.REFLECTIONMAP_3D = false;
  28268. _this.REFLECTIONMAP_SPHERICAL = false;
  28269. _this.REFLECTIONMAP_PLANAR = false;
  28270. _this.REFLECTIONMAP_CUBIC = false;
  28271. _this.REFLECTIONMAP_PROJECTION = false;
  28272. _this.REFLECTIONMAP_SKYBOX = false;
  28273. _this.REFLECTIONMAP_EXPLICIT = false;
  28274. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28275. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28276. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28277. _this.INVERTCUBICMAP = false;
  28278. _this.LOGARITHMICDEPTH = false;
  28279. _this.REFRACTION = false;
  28280. _this.REFRACTIONMAP_3D = false;
  28281. _this.REFLECTIONOVERALPHA = false;
  28282. _this.INVERTNORMALMAPX = false;
  28283. _this.INVERTNORMALMAPY = false;
  28284. _this.TWOSIDEDLIGHTING = false;
  28285. _this.SHADOWFLOAT = false;
  28286. _this.CAMERACOLORGRADING = false;
  28287. _this.CAMERACOLORCURVES = false;
  28288. _this.MORPHTARGETS = false;
  28289. _this.MORPHTARGETS_NORMAL = false;
  28290. _this.MORPHTARGETS_TANGENT = false;
  28291. _this.NUM_MORPH_INFLUENCERS = 0;
  28292. _this.USERIGHTHANDEDSYSTEM = false;
  28293. _this.rebuild();
  28294. return _this;
  28295. }
  28296. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  28297. var modes = [
  28298. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  28299. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  28300. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  28301. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  28302. ];
  28303. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  28304. var mode = modes_1[_i];
  28305. this[mode] = (mode === modeToEnable);
  28306. }
  28307. };
  28308. return StandardMaterialDefines;
  28309. }(BABYLON.MaterialDefines));
  28310. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  28311. var StandardMaterial = (function (_super) {
  28312. __extends(StandardMaterial, _super);
  28313. function StandardMaterial(name, scene) {
  28314. var _this = _super.call(this, name, scene) || this;
  28315. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28316. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  28317. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  28318. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28319. _this.specularPower = 64;
  28320. _this._useAlphaFromDiffuseTexture = false;
  28321. _this._useEmissiveAsIllumination = false;
  28322. _this._linkEmissiveWithDiffuse = false;
  28323. _this._useSpecularOverAlpha = false;
  28324. _this._useReflectionOverAlpha = false;
  28325. _this._disableLighting = false;
  28326. _this._useParallax = false;
  28327. _this._useParallaxOcclusion = false;
  28328. _this.parallaxScaleBias = 0.05;
  28329. _this._roughness = 0;
  28330. _this.indexOfRefraction = 0.98;
  28331. _this.invertRefractionY = true;
  28332. _this._useLightmapAsShadowmap = false;
  28333. _this._useReflectionFresnelFromSpecular = false;
  28334. _this._useGlossinessFromSpecularMapAlpha = false;
  28335. _this._maxSimultaneousLights = 4;
  28336. /**
  28337. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28338. */
  28339. _this._invertNormalMapX = false;
  28340. /**
  28341. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28342. */
  28343. _this._invertNormalMapY = false;
  28344. /**
  28345. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28346. */
  28347. _this._twoSidedLighting = false;
  28348. /**
  28349. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28350. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28351. * 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;
  28352. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28353. */
  28354. _this._cameraColorCurves = null;
  28355. _this._renderTargets = new BABYLON.SmartArray(16);
  28356. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28357. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28358. _this.getRenderTargetTextures = function () {
  28359. _this._renderTargets.reset();
  28360. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  28361. _this._renderTargets.push(_this._reflectionTexture);
  28362. }
  28363. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  28364. _this._renderTargets.push(_this._refractionTexture);
  28365. }
  28366. return _this._renderTargets;
  28367. };
  28368. return _this;
  28369. }
  28370. StandardMaterial.prototype.getClassName = function () {
  28371. return "StandardMaterial";
  28372. };
  28373. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  28374. get: function () {
  28375. return this._useLogarithmicDepth;
  28376. },
  28377. set: function (value) {
  28378. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28379. this._markAllSubMeshesAsMiscDirty();
  28380. },
  28381. enumerable: true,
  28382. configurable: true
  28383. });
  28384. StandardMaterial.prototype.needAlphaBlending = function () {
  28385. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  28386. };
  28387. StandardMaterial.prototype.needAlphaTesting = function () {
  28388. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  28389. };
  28390. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  28391. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  28392. };
  28393. StandardMaterial.prototype.getAlphaTestTexture = function () {
  28394. return this._diffuseTexture;
  28395. };
  28396. /**
  28397. * Child classes can use it to update shaders
  28398. */
  28399. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28400. if (this.isFrozen) {
  28401. if (this._wasPreviouslyReady && subMesh.effect) {
  28402. return true;
  28403. }
  28404. }
  28405. if (!subMesh._materialDefines) {
  28406. subMesh._materialDefines = new StandardMaterialDefines();
  28407. }
  28408. var scene = this.getScene();
  28409. var defines = subMesh._materialDefines;
  28410. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  28411. if (defines._renderId === scene.getRenderId()) {
  28412. return true;
  28413. }
  28414. }
  28415. var engine = scene.getEngine();
  28416. // Lights
  28417. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  28418. // Textures
  28419. if (defines._areTexturesDirty) {
  28420. defines._needUVs = false;
  28421. if (scene.texturesEnabled) {
  28422. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28423. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  28424. return false;
  28425. }
  28426. else {
  28427. defines._needUVs = true;
  28428. defines.DIFFUSE = true;
  28429. }
  28430. }
  28431. else {
  28432. defines.DIFFUSE = false;
  28433. }
  28434. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28435. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  28436. return false;
  28437. }
  28438. else {
  28439. defines._needUVs = true;
  28440. defines.AMBIENT = true;
  28441. }
  28442. }
  28443. else {
  28444. defines.AMBIENT = false;
  28445. }
  28446. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28447. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  28448. return false;
  28449. }
  28450. else {
  28451. defines._needUVs = true;
  28452. defines.OPACITY = true;
  28453. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  28454. }
  28455. }
  28456. else {
  28457. defines.OPACITY = false;
  28458. }
  28459. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28460. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  28461. return false;
  28462. }
  28463. else {
  28464. defines._needNormals = true;
  28465. defines.REFLECTION = true;
  28466. defines.ROUGHNESS = (this._roughness > 0);
  28467. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  28468. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  28469. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  28470. switch (this._reflectionTexture.coordinatesMode) {
  28471. case BABYLON.Texture.CUBIC_MODE:
  28472. case BABYLON.Texture.INVCUBIC_MODE:
  28473. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  28474. break;
  28475. case BABYLON.Texture.EXPLICIT_MODE:
  28476. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  28477. break;
  28478. case BABYLON.Texture.PLANAR_MODE:
  28479. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  28480. break;
  28481. case BABYLON.Texture.PROJECTION_MODE:
  28482. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  28483. break;
  28484. case BABYLON.Texture.SKYBOX_MODE:
  28485. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  28486. break;
  28487. case BABYLON.Texture.SPHERICAL_MODE:
  28488. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  28489. break;
  28490. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28491. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  28492. break;
  28493. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28494. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  28495. break;
  28496. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28497. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  28498. break;
  28499. }
  28500. }
  28501. }
  28502. else {
  28503. defines.REFLECTION = false;
  28504. }
  28505. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28506. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  28507. return false;
  28508. }
  28509. else {
  28510. defines._needUVs = true;
  28511. defines.EMISSIVE = true;
  28512. }
  28513. }
  28514. else {
  28515. defines.EMISSIVE = false;
  28516. }
  28517. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28518. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  28519. return false;
  28520. }
  28521. else {
  28522. defines._needUVs = true;
  28523. defines.LIGHTMAP = true;
  28524. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  28525. }
  28526. }
  28527. else {
  28528. defines.LIGHTMAP = false;
  28529. }
  28530. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28531. if (!this._specularTexture.isReadyOrNotBlocking()) {
  28532. return false;
  28533. }
  28534. else {
  28535. defines._needUVs = true;
  28536. defines.SPECULAR = true;
  28537. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  28538. }
  28539. }
  28540. else {
  28541. defines.SPECULAR = false;
  28542. }
  28543. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  28544. // Bump texure can not be none blocking.
  28545. if (!this._bumpTexture.isReady()) {
  28546. return false;
  28547. }
  28548. else {
  28549. defines._needUVs = true;
  28550. defines.BUMP = true;
  28551. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  28552. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  28553. defines.PARALLAX = this._useParallax;
  28554. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  28555. }
  28556. }
  28557. else {
  28558. defines.BUMP = false;
  28559. }
  28560. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28561. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  28562. return false;
  28563. }
  28564. else {
  28565. defines._needUVs = true;
  28566. defines.REFRACTION = true;
  28567. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  28568. }
  28569. }
  28570. else {
  28571. defines.REFRACTION = false;
  28572. }
  28573. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28574. // Camera Color Grading can not be none blocking.
  28575. if (!this._cameraColorGradingTexture.isReady()) {
  28576. return false;
  28577. }
  28578. else {
  28579. defines.CAMERACOLORGRADING = true;
  28580. }
  28581. }
  28582. else {
  28583. defines.CAMERACOLORGRADING = false;
  28584. }
  28585. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  28586. }
  28587. else {
  28588. defines.DIFFUSE = false;
  28589. defines.AMBIENT = false;
  28590. defines.OPACITY = false;
  28591. defines.REFLECTION = false;
  28592. defines.EMISSIVE = false;
  28593. defines.LIGHTMAP = false;
  28594. defines.BUMP = false;
  28595. defines.REFRACTION = false;
  28596. defines.CAMERACOLORGRADING = false;
  28597. }
  28598. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  28599. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  28600. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  28601. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  28602. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  28603. }
  28604. if (defines._areFresnelDirty) {
  28605. if (StandardMaterial.FresnelEnabled) {
  28606. // Fresnel
  28607. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  28608. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  28609. this._reflectionFresnelParameters) {
  28610. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  28611. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  28612. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  28613. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  28614. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  28615. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  28616. defines._needNormals = true;
  28617. defines.FRESNEL = true;
  28618. }
  28619. }
  28620. else {
  28621. defines.FRESNEL = false;
  28622. }
  28623. }
  28624. // Misc.
  28625. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  28626. // Attribs
  28627. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  28628. // Values that need to be evaluated on every frame
  28629. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  28630. if (scene._mirroredCameraPosition && defines.BUMP) {
  28631. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  28632. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  28633. defines.markAsUnprocessed();
  28634. }
  28635. // Get correct effect
  28636. if (defines.isDirty) {
  28637. defines.markAsProcessed();
  28638. scene.resetCachedMaterial();
  28639. // Fallbacks
  28640. var fallbacks = new BABYLON.EffectFallbacks();
  28641. if (defines.REFLECTION) {
  28642. fallbacks.addFallback(0, "REFLECTION");
  28643. }
  28644. if (defines.SPECULAR) {
  28645. fallbacks.addFallback(0, "SPECULAR");
  28646. }
  28647. if (defines.BUMP) {
  28648. fallbacks.addFallback(0, "BUMP");
  28649. }
  28650. if (defines.PARALLAX) {
  28651. fallbacks.addFallback(1, "PARALLAX");
  28652. }
  28653. if (defines.PARALLAXOCCLUSION) {
  28654. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  28655. }
  28656. if (defines.SPECULAROVERALPHA) {
  28657. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  28658. }
  28659. if (defines.FOG) {
  28660. fallbacks.addFallback(1, "FOG");
  28661. }
  28662. if (defines.POINTSIZE) {
  28663. fallbacks.addFallback(0, "POINTSIZE");
  28664. }
  28665. if (defines.LOGARITHMICDEPTH) {
  28666. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  28667. }
  28668. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  28669. if (defines.SPECULARTERM) {
  28670. fallbacks.addFallback(0, "SPECULARTERM");
  28671. }
  28672. if (defines.DIFFUSEFRESNEL) {
  28673. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  28674. }
  28675. if (defines.OPACITYFRESNEL) {
  28676. fallbacks.addFallback(2, "OPACITYFRESNEL");
  28677. }
  28678. if (defines.REFLECTIONFRESNEL) {
  28679. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  28680. }
  28681. if (defines.EMISSIVEFRESNEL) {
  28682. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  28683. }
  28684. if (defines.FRESNEL) {
  28685. fallbacks.addFallback(4, "FRESNEL");
  28686. }
  28687. //Attributes
  28688. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28689. if (defines.NORMAL) {
  28690. attribs.push(BABYLON.VertexBuffer.NormalKind);
  28691. }
  28692. if (defines.UV1) {
  28693. attribs.push(BABYLON.VertexBuffer.UVKind);
  28694. }
  28695. if (defines.UV2) {
  28696. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28697. }
  28698. if (defines.VERTEXCOLOR) {
  28699. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28700. }
  28701. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  28702. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  28703. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  28704. var shaderName = "default";
  28705. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  28706. "vFogInfos", "vFogColor", "pointSize",
  28707. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  28708. "mBones",
  28709. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  28710. "depthValues",
  28711. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  28712. "logarithmicDepthConstant"
  28713. ];
  28714. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  28715. var uniformBuffers = ["Material", "Scene"];
  28716. if (defines.CAMERACOLORCURVES) {
  28717. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  28718. }
  28719. if (defines.CAMERACOLORGRADING) {
  28720. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  28721. }
  28722. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  28723. uniformsNames: uniforms,
  28724. uniformBuffersNames: uniformBuffers,
  28725. samplers: samplers,
  28726. defines: defines,
  28727. maxSimultaneousLights: this._maxSimultaneousLights
  28728. });
  28729. if (this.customShaderNameResolve) {
  28730. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  28731. }
  28732. var join = defines.toString();
  28733. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  28734. attributes: attribs,
  28735. uniformsNames: uniforms,
  28736. uniformBuffersNames: uniformBuffers,
  28737. samplers: samplers,
  28738. defines: join,
  28739. fallbacks: fallbacks,
  28740. onCompiled: this.onCompiled,
  28741. onError: this.onError,
  28742. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  28743. }, engine), defines);
  28744. this.buildUniformLayout();
  28745. }
  28746. if (!subMesh.effect.isReady()) {
  28747. return false;
  28748. }
  28749. defines._renderId = scene.getRenderId();
  28750. this._wasPreviouslyReady = true;
  28751. return true;
  28752. };
  28753. StandardMaterial.prototype.buildUniformLayout = function () {
  28754. // Order is important !
  28755. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  28756. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  28757. this._uniformBuffer.addUniform("opacityParts", 4);
  28758. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  28759. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  28760. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  28761. this._uniformBuffer.addUniform("refractionRightColor", 4);
  28762. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  28763. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  28764. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  28765. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  28766. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  28767. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  28768. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  28769. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  28770. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  28771. this._uniformBuffer.addUniform("vBumpInfos", 3);
  28772. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  28773. this._uniformBuffer.addUniform("ambientMatrix", 16);
  28774. this._uniformBuffer.addUniform("opacityMatrix", 16);
  28775. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  28776. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  28777. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  28778. this._uniformBuffer.addUniform("specularMatrix", 16);
  28779. this._uniformBuffer.addUniform("bumpMatrix", 16);
  28780. this._uniformBuffer.addUniform("refractionMatrix", 16);
  28781. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  28782. this._uniformBuffer.addUniform("vSpecularColor", 4);
  28783. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  28784. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  28785. this._uniformBuffer.addUniform("pointSize", 1);
  28786. this._uniformBuffer.create();
  28787. };
  28788. StandardMaterial.prototype.unbind = function () {
  28789. if (this._activeEffect) {
  28790. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  28791. this._activeEffect.setTexture("reflection2DSampler", null);
  28792. }
  28793. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  28794. this._activeEffect.setTexture("refraction2DSampler", null);
  28795. }
  28796. }
  28797. _super.prototype.unbind.call(this);
  28798. };
  28799. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28800. var scene = this.getScene();
  28801. var defines = subMesh._materialDefines;
  28802. if (!defines) {
  28803. return;
  28804. }
  28805. var effect = subMesh.effect;
  28806. this._activeEffect = effect;
  28807. // Matrices
  28808. this.bindOnlyWorldMatrix(world);
  28809. // Bones
  28810. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  28811. if (this._mustRebind(scene, effect, mesh.visibility)) {
  28812. this._uniformBuffer.bindToEffect(effect, "Material");
  28813. this.bindViewProjection(effect);
  28814. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  28815. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  28816. // Fresnel
  28817. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  28818. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  28819. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  28820. }
  28821. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28822. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  28823. }
  28824. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  28825. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  28826. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  28827. }
  28828. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  28829. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  28830. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  28831. }
  28832. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28833. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  28834. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  28835. }
  28836. }
  28837. // Textures
  28838. if (scene.texturesEnabled) {
  28839. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28840. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  28841. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  28842. }
  28843. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28844. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  28845. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  28846. }
  28847. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28848. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  28849. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  28850. }
  28851. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28852. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  28853. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  28854. }
  28855. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28856. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  28857. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  28858. }
  28859. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28860. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  28861. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  28862. }
  28863. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28864. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  28865. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  28866. }
  28867. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28868. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  28869. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  28870. }
  28871. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28872. var depth = 1.0;
  28873. if (!this._refractionTexture.isCube) {
  28874. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  28875. if (this._refractionTexture.depth) {
  28876. depth = this._refractionTexture.depth;
  28877. }
  28878. }
  28879. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  28880. }
  28881. }
  28882. // Point size
  28883. if (this.pointsCloud) {
  28884. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  28885. }
  28886. if (defines.SPECULARTERM) {
  28887. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  28888. }
  28889. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  28890. // Diffuse
  28891. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  28892. }
  28893. // Textures
  28894. if (scene.texturesEnabled) {
  28895. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  28896. effect.setTexture("diffuseSampler", this._diffuseTexture);
  28897. }
  28898. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  28899. effect.setTexture("ambientSampler", this._ambientTexture);
  28900. }
  28901. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  28902. effect.setTexture("opacitySampler", this._opacityTexture);
  28903. }
  28904. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  28905. if (this._reflectionTexture.isCube) {
  28906. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  28907. }
  28908. else {
  28909. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  28910. }
  28911. }
  28912. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  28913. effect.setTexture("emissiveSampler", this._emissiveTexture);
  28914. }
  28915. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  28916. effect.setTexture("lightmapSampler", this._lightmapTexture);
  28917. }
  28918. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  28919. effect.setTexture("specularSampler", this._specularTexture);
  28920. }
  28921. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  28922. effect.setTexture("bumpSampler", this._bumpTexture);
  28923. }
  28924. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  28925. var depth = 1.0;
  28926. if (this._refractionTexture.isCube) {
  28927. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  28928. }
  28929. else {
  28930. effect.setTexture("refraction2DSampler", this._refractionTexture);
  28931. }
  28932. }
  28933. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  28934. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  28935. }
  28936. }
  28937. // Clip plane
  28938. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  28939. // Colors
  28940. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  28941. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  28942. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  28943. }
  28944. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  28945. // Lights
  28946. if (scene.lightsEnabled && !this._disableLighting) {
  28947. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  28948. }
  28949. // View
  28950. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  28951. this.bindView(effect);
  28952. }
  28953. // Fog
  28954. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  28955. // Morph targets
  28956. if (defines.NUM_MORPH_INFLUENCERS) {
  28957. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  28958. }
  28959. // Log. depth
  28960. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  28961. // Color Curves
  28962. if (this._cameraColorCurves) {
  28963. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  28964. }
  28965. }
  28966. this._uniformBuffer.update();
  28967. this._afterBind(mesh, this._activeEffect);
  28968. };
  28969. StandardMaterial.prototype.getAnimatables = function () {
  28970. var results = [];
  28971. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  28972. results.push(this._diffuseTexture);
  28973. }
  28974. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  28975. results.push(this._ambientTexture);
  28976. }
  28977. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  28978. results.push(this._opacityTexture);
  28979. }
  28980. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  28981. results.push(this._reflectionTexture);
  28982. }
  28983. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  28984. results.push(this._emissiveTexture);
  28985. }
  28986. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  28987. results.push(this._specularTexture);
  28988. }
  28989. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  28990. results.push(this._bumpTexture);
  28991. }
  28992. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  28993. results.push(this._lightmapTexture);
  28994. }
  28995. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  28996. results.push(this._refractionTexture);
  28997. }
  28998. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  28999. results.push(this._cameraColorGradingTexture);
  29000. }
  29001. return results;
  29002. };
  29003. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29004. if (forceDisposeTextures) {
  29005. if (this._diffuseTexture) {
  29006. this._diffuseTexture.dispose();
  29007. }
  29008. if (this._ambientTexture) {
  29009. this._ambientTexture.dispose();
  29010. }
  29011. if (this._opacityTexture) {
  29012. this._opacityTexture.dispose();
  29013. }
  29014. if (this._reflectionTexture) {
  29015. this._reflectionTexture.dispose();
  29016. }
  29017. if (this._emissiveTexture) {
  29018. this._emissiveTexture.dispose();
  29019. }
  29020. if (this._specularTexture) {
  29021. this._specularTexture.dispose();
  29022. }
  29023. if (this._bumpTexture) {
  29024. this._bumpTexture.dispose();
  29025. }
  29026. if (this._lightmapTexture) {
  29027. this._lightmapTexture.dispose();
  29028. }
  29029. if (this._refractionTexture) {
  29030. this._refractionTexture.dispose();
  29031. }
  29032. if (this._cameraColorGradingTexture) {
  29033. this._cameraColorGradingTexture.dispose();
  29034. }
  29035. }
  29036. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29037. };
  29038. StandardMaterial.prototype.clone = function (name) {
  29039. var _this = this;
  29040. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  29041. result.name = name;
  29042. result.id = name;
  29043. return result;
  29044. };
  29045. StandardMaterial.prototype.serialize = function () {
  29046. return BABYLON.SerializationHelper.Serialize(this);
  29047. };
  29048. // Statics
  29049. StandardMaterial.Parse = function (source, scene, rootUrl) {
  29050. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  29051. };
  29052. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  29053. get: function () {
  29054. return StandardMaterial._DiffuseTextureEnabled;
  29055. },
  29056. set: function (value) {
  29057. if (StandardMaterial._DiffuseTextureEnabled === value) {
  29058. return;
  29059. }
  29060. StandardMaterial._DiffuseTextureEnabled = value;
  29061. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29062. },
  29063. enumerable: true,
  29064. configurable: true
  29065. });
  29066. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  29067. get: function () {
  29068. return StandardMaterial._AmbientTextureEnabled;
  29069. },
  29070. set: function (value) {
  29071. if (StandardMaterial._AmbientTextureEnabled === value) {
  29072. return;
  29073. }
  29074. StandardMaterial._AmbientTextureEnabled = value;
  29075. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29076. },
  29077. enumerable: true,
  29078. configurable: true
  29079. });
  29080. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  29081. get: function () {
  29082. return StandardMaterial._OpacityTextureEnabled;
  29083. },
  29084. set: function (value) {
  29085. if (StandardMaterial._OpacityTextureEnabled === value) {
  29086. return;
  29087. }
  29088. StandardMaterial._OpacityTextureEnabled = value;
  29089. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29090. },
  29091. enumerable: true,
  29092. configurable: true
  29093. });
  29094. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  29095. get: function () {
  29096. return StandardMaterial._ReflectionTextureEnabled;
  29097. },
  29098. set: function (value) {
  29099. if (StandardMaterial._ReflectionTextureEnabled === value) {
  29100. return;
  29101. }
  29102. StandardMaterial._ReflectionTextureEnabled = value;
  29103. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29104. },
  29105. enumerable: true,
  29106. configurable: true
  29107. });
  29108. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  29109. get: function () {
  29110. return StandardMaterial._EmissiveTextureEnabled;
  29111. },
  29112. set: function (value) {
  29113. if (StandardMaterial._EmissiveTextureEnabled === value) {
  29114. return;
  29115. }
  29116. StandardMaterial._EmissiveTextureEnabled = value;
  29117. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29118. },
  29119. enumerable: true,
  29120. configurable: true
  29121. });
  29122. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  29123. get: function () {
  29124. return StandardMaterial._SpecularTextureEnabled;
  29125. },
  29126. set: function (value) {
  29127. if (StandardMaterial._SpecularTextureEnabled === value) {
  29128. return;
  29129. }
  29130. StandardMaterial._SpecularTextureEnabled = value;
  29131. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29132. },
  29133. enumerable: true,
  29134. configurable: true
  29135. });
  29136. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  29137. get: function () {
  29138. return StandardMaterial._BumpTextureEnabled;
  29139. },
  29140. set: function (value) {
  29141. if (StandardMaterial._BumpTextureEnabled === value) {
  29142. return;
  29143. }
  29144. StandardMaterial._BumpTextureEnabled = value;
  29145. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29146. },
  29147. enumerable: true,
  29148. configurable: true
  29149. });
  29150. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  29151. get: function () {
  29152. return StandardMaterial._LightmapTextureEnabled;
  29153. },
  29154. set: function (value) {
  29155. if (StandardMaterial._LightmapTextureEnabled === value) {
  29156. return;
  29157. }
  29158. StandardMaterial._LightmapTextureEnabled = value;
  29159. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29160. },
  29161. enumerable: true,
  29162. configurable: true
  29163. });
  29164. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  29165. get: function () {
  29166. return StandardMaterial._RefractionTextureEnabled;
  29167. },
  29168. set: function (value) {
  29169. if (StandardMaterial._RefractionTextureEnabled === value) {
  29170. return;
  29171. }
  29172. StandardMaterial._RefractionTextureEnabled = value;
  29173. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29174. },
  29175. enumerable: true,
  29176. configurable: true
  29177. });
  29178. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  29179. get: function () {
  29180. return StandardMaterial._ColorGradingTextureEnabled;
  29181. },
  29182. set: function (value) {
  29183. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  29184. return;
  29185. }
  29186. StandardMaterial._ColorGradingTextureEnabled = value;
  29187. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29188. },
  29189. enumerable: true,
  29190. configurable: true
  29191. });
  29192. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  29193. get: function () {
  29194. return StandardMaterial._FresnelEnabled;
  29195. },
  29196. set: function (value) {
  29197. if (StandardMaterial._FresnelEnabled === value) {
  29198. return;
  29199. }
  29200. StandardMaterial._FresnelEnabled = value;
  29201. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  29202. },
  29203. enumerable: true,
  29204. configurable: true
  29205. });
  29206. return StandardMaterial;
  29207. }(BABYLON.PushMaterial));
  29208. // Flags used to enable or disable a type of texture for all Standard Materials
  29209. StandardMaterial._DiffuseTextureEnabled = true;
  29210. StandardMaterial._AmbientTextureEnabled = true;
  29211. StandardMaterial._OpacityTextureEnabled = true;
  29212. StandardMaterial._ReflectionTextureEnabled = true;
  29213. StandardMaterial._EmissiveTextureEnabled = true;
  29214. StandardMaterial._SpecularTextureEnabled = true;
  29215. StandardMaterial._BumpTextureEnabled = true;
  29216. StandardMaterial._LightmapTextureEnabled = true;
  29217. StandardMaterial._RefractionTextureEnabled = true;
  29218. StandardMaterial._ColorGradingTextureEnabled = true;
  29219. StandardMaterial._FresnelEnabled = true;
  29220. __decorate([
  29221. BABYLON.serializeAsTexture("diffuseTexture")
  29222. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  29223. __decorate([
  29224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29225. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  29226. __decorate([
  29227. BABYLON.serializeAsTexture("ambientTexture")
  29228. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  29229. __decorate([
  29230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29231. ], StandardMaterial.prototype, "ambientTexture", void 0);
  29232. __decorate([
  29233. BABYLON.serializeAsTexture("opacityTexture")
  29234. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  29235. __decorate([
  29236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29237. ], StandardMaterial.prototype, "opacityTexture", void 0);
  29238. __decorate([
  29239. BABYLON.serializeAsTexture("reflectionTexture")
  29240. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  29241. __decorate([
  29242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29243. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  29244. __decorate([
  29245. BABYLON.serializeAsTexture("emissiveTexture")
  29246. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  29247. __decorate([
  29248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29249. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  29250. __decorate([
  29251. BABYLON.serializeAsTexture("specularTexture")
  29252. ], StandardMaterial.prototype, "_specularTexture", void 0);
  29253. __decorate([
  29254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29255. ], StandardMaterial.prototype, "specularTexture", void 0);
  29256. __decorate([
  29257. BABYLON.serializeAsTexture("bumpTexture")
  29258. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  29259. __decorate([
  29260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29261. ], StandardMaterial.prototype, "bumpTexture", void 0);
  29262. __decorate([
  29263. BABYLON.serializeAsTexture("lightmapTexture")
  29264. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  29265. __decorate([
  29266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29267. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  29268. __decorate([
  29269. BABYLON.serializeAsTexture("refractionTexture")
  29270. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  29271. __decorate([
  29272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29273. ], StandardMaterial.prototype, "refractionTexture", void 0);
  29274. __decorate([
  29275. BABYLON.serializeAsColor3("ambient")
  29276. ], StandardMaterial.prototype, "ambientColor", void 0);
  29277. __decorate([
  29278. BABYLON.serializeAsColor3("diffuse")
  29279. ], StandardMaterial.prototype, "diffuseColor", void 0);
  29280. __decorate([
  29281. BABYLON.serializeAsColor3("specular")
  29282. ], StandardMaterial.prototype, "specularColor", void 0);
  29283. __decorate([
  29284. BABYLON.serializeAsColor3("emissive")
  29285. ], StandardMaterial.prototype, "emissiveColor", void 0);
  29286. __decorate([
  29287. BABYLON.serialize()
  29288. ], StandardMaterial.prototype, "specularPower", void 0);
  29289. __decorate([
  29290. BABYLON.serialize("useAlphaFromDiffuseTexture")
  29291. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  29292. __decorate([
  29293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29294. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  29295. __decorate([
  29296. BABYLON.serialize("useEmissiveAsIllumination")
  29297. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  29298. __decorate([
  29299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29300. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29301. __decorate([
  29302. BABYLON.serialize("linkEmissiveWithDiffuse")
  29303. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  29304. __decorate([
  29305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29306. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  29307. __decorate([
  29308. BABYLON.serialize("useSpecularOverAlpha")
  29309. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  29310. __decorate([
  29311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29312. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  29313. __decorate([
  29314. BABYLON.serialize("useReflectionOverAlpha")
  29315. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  29316. __decorate([
  29317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29318. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  29319. __decorate([
  29320. BABYLON.serialize("disableLighting")
  29321. ], StandardMaterial.prototype, "_disableLighting", void 0);
  29322. __decorate([
  29323. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29324. ], StandardMaterial.prototype, "disableLighting", void 0);
  29325. __decorate([
  29326. BABYLON.serialize("useParallax")
  29327. ], StandardMaterial.prototype, "_useParallax", void 0);
  29328. __decorate([
  29329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29330. ], StandardMaterial.prototype, "useParallax", void 0);
  29331. __decorate([
  29332. BABYLON.serialize("useParallaxOcclusion")
  29333. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  29334. __decorate([
  29335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29336. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  29337. __decorate([
  29338. BABYLON.serialize()
  29339. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  29340. __decorate([
  29341. BABYLON.serialize("roughness")
  29342. ], StandardMaterial.prototype, "_roughness", void 0);
  29343. __decorate([
  29344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29345. ], StandardMaterial.prototype, "roughness", void 0);
  29346. __decorate([
  29347. BABYLON.serialize()
  29348. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  29349. __decorate([
  29350. BABYLON.serialize()
  29351. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  29352. __decorate([
  29353. BABYLON.serialize("useLightmapAsShadowmap")
  29354. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  29355. __decorate([
  29356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29357. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29358. __decorate([
  29359. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  29360. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  29361. __decorate([
  29362. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29363. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  29364. __decorate([
  29365. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  29366. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  29367. __decorate([
  29368. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29369. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  29370. __decorate([
  29371. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  29372. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  29373. __decorate([
  29374. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29375. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  29376. __decorate([
  29377. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  29378. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  29379. __decorate([
  29380. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29381. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  29382. __decorate([
  29383. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  29384. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  29385. __decorate([
  29386. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29387. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  29388. __decorate([
  29389. BABYLON.serialize("useReflectionFresnelFromSpecular")
  29390. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  29391. __decorate([
  29392. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  29393. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  29394. __decorate([
  29395. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  29396. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  29397. __decorate([
  29398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29399. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  29400. __decorate([
  29401. BABYLON.serialize("maxSimultaneousLights")
  29402. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  29403. __decorate([
  29404. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  29405. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  29406. __decorate([
  29407. BABYLON.serialize("invertNormalMapX")
  29408. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  29409. __decorate([
  29410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29411. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  29412. __decorate([
  29413. BABYLON.serialize("invertNormalMapY")
  29414. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  29415. __decorate([
  29416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29417. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  29418. __decorate([
  29419. BABYLON.serialize("twoSidedLighting")
  29420. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  29421. __decorate([
  29422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29423. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  29424. __decorate([
  29425. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  29426. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  29427. __decorate([
  29428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29429. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  29430. __decorate([
  29431. BABYLON.serializeAsColorCurves("cameraColorCurves")
  29432. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  29433. __decorate([
  29434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  29435. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  29436. __decorate([
  29437. BABYLON.serialize()
  29438. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  29439. BABYLON.StandardMaterial = StandardMaterial;
  29440. })(BABYLON || (BABYLON = {}));
  29441. //# sourceMappingURL=babylon.standardMaterial.js.map
  29442. var BABYLON;
  29443. (function (BABYLON) {
  29444. var PBRMaterialDefines = (function (_super) {
  29445. __extends(PBRMaterialDefines, _super);
  29446. function PBRMaterialDefines() {
  29447. var _this = _super.call(this) || this;
  29448. _this.PBR = true;
  29449. _this.ALBEDO = false;
  29450. _this.AMBIENT = false;
  29451. _this.AMBIENTINGRAYSCALE = false;
  29452. _this.OPACITY = false;
  29453. _this.OPACITYRGB = false;
  29454. _this.REFLECTION = false;
  29455. _this.EMISSIVE = false;
  29456. _this.REFLECTIVITY = false;
  29457. _this.BUMP = false;
  29458. _this.PARALLAX = false;
  29459. _this.PARALLAXOCCLUSION = false;
  29460. _this.SPECULAROVERALPHA = false;
  29461. _this.CLIPPLANE = false;
  29462. _this.ALPHATEST = false;
  29463. _this.ALPHAFROMALBEDO = false;
  29464. _this.POINTSIZE = false;
  29465. _this.FOG = false;
  29466. _this.SPECULARTERM = false;
  29467. _this.OPACITYFRESNEL = false;
  29468. _this.EMISSIVEFRESNEL = false;
  29469. _this.FRESNEL = false;
  29470. _this.NORMAL = false;
  29471. _this.TANGENT = false;
  29472. _this.UV1 = false;
  29473. _this.UV2 = false;
  29474. _this.VERTEXCOLOR = false;
  29475. _this.VERTEXALPHA = false;
  29476. _this.NUM_BONE_INFLUENCERS = 0;
  29477. _this.BonesPerMesh = 0;
  29478. _this.INSTANCES = false;
  29479. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  29480. _this.MICROSURFACEAUTOMATIC = false;
  29481. _this.EMISSIVEASILLUMINATION = false;
  29482. _this.LIGHTMAP = false;
  29483. _this.USELIGHTMAPASSHADOWMAP = false;
  29484. _this.REFLECTIONMAP_3D = false;
  29485. _this.REFLECTIONMAP_SPHERICAL = false;
  29486. _this.REFLECTIONMAP_PLANAR = false;
  29487. _this.REFLECTIONMAP_CUBIC = false;
  29488. _this.REFLECTIONMAP_PROJECTION = false;
  29489. _this.REFLECTIONMAP_SKYBOX = false;
  29490. _this.REFLECTIONMAP_EXPLICIT = false;
  29491. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29492. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29493. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  29494. _this.INVERTCUBICMAP = false;
  29495. _this.LOGARITHMICDEPTH = false;
  29496. _this.CAMERATONEMAP = false;
  29497. _this.CAMERACONTRAST = false;
  29498. _this.CAMERACOLORGRADING = false;
  29499. _this.CAMERACOLORCURVES = false;
  29500. _this.USESPHERICALFROMREFLECTIONMAP = false;
  29501. _this.REFRACTION = false;
  29502. _this.REFRACTIONMAP_3D = false;
  29503. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  29504. _this.REFRACTIONMAPINLINEARSPACE = false;
  29505. _this.LODBASEDMICROSFURACE = false;
  29506. _this.USEPHYSICALLIGHTFALLOFF = false;
  29507. _this.RADIANCEOVERALPHA = false;
  29508. _this.USEPMREMREFLECTION = false;
  29509. _this.USEPMREMREFRACTION = false;
  29510. _this.INVERTNORMALMAPX = false;
  29511. _this.INVERTNORMALMAPY = false;
  29512. _this.TWOSIDEDLIGHTING = false;
  29513. _this.SHADOWFLOAT = false;
  29514. _this.NORMALXYSCALE = true;
  29515. _this.USERIGHTHANDEDSYSTEM = false;
  29516. _this.METALLICWORKFLOW = false;
  29517. _this.METALLICMAP = false;
  29518. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  29519. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  29520. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  29521. _this.AOSTOREINMETALMAPRED = false;
  29522. _this.MICROSURFACEMAP = false;
  29523. _this.MORPHTARGETS = false;
  29524. _this.MORPHTARGETS_NORMAL = false;
  29525. _this.MORPHTARGETS_TANGENT = false;
  29526. _this.NUM_MORPH_INFLUENCERS = 0;
  29527. _this.ALPHATESTVALUE = 0.4;
  29528. _this.LDROUTPUT = true;
  29529. _this.rebuild();
  29530. return _this;
  29531. }
  29532. PBRMaterialDefines.prototype.reset = function () {
  29533. _super.prototype.reset.call(this);
  29534. this.ALPHATESTVALUE = 0.4;
  29535. this.PBR = true;
  29536. };
  29537. return PBRMaterialDefines;
  29538. }(BABYLON.MaterialDefines));
  29539. /**
  29540. * The Physically based material base class of BJS.
  29541. *
  29542. * This offers the main features of a standard PBR material.
  29543. * For more information, please refer to the documentation :
  29544. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  29545. */
  29546. var PBRBaseMaterial = (function (_super) {
  29547. __extends(PBRBaseMaterial, _super);
  29548. /**
  29549. * Instantiates a new PBRMaterial instance.
  29550. *
  29551. * @param name The material name
  29552. * @param scene The scene the material will be use in.
  29553. */
  29554. function PBRBaseMaterial(name, scene) {
  29555. var _this = _super.call(this, name, scene) || this;
  29556. /**
  29557. * Intensity of the direct lights e.g. the four lights available in your scene.
  29558. * This impacts both the direct diffuse and specular highlights.
  29559. */
  29560. _this._directIntensity = 1.0;
  29561. /**
  29562. * Intensity of the emissive part of the material.
  29563. * This helps controlling the emissive effect without modifying the emissive color.
  29564. */
  29565. _this._emissiveIntensity = 1.0;
  29566. /**
  29567. * Intensity of the environment e.g. how much the environment will light the object
  29568. * either through harmonics for rough material or through the refelction for shiny ones.
  29569. */
  29570. _this._environmentIntensity = 1.0;
  29571. /**
  29572. * This is a special control allowing the reduction of the specular highlights coming from the
  29573. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  29574. */
  29575. _this._specularIntensity = 1.0;
  29576. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  29577. /**
  29578. * Debug Control allowing disabling the bump map on this material.
  29579. */
  29580. _this._disableBumpMap = false;
  29581. /**
  29582. * The camera exposure used on this material.
  29583. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  29584. * This corresponds to a photographic exposure.
  29585. */
  29586. _this._cameraExposure = 1.0;
  29587. /**
  29588. * The camera contrast used on this material.
  29589. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  29590. */
  29591. _this._cameraContrast = 1.0;
  29592. /**
  29593. * Color Grading 2D Lookup Texture.
  29594. * This allows special effects like sepia, black and white to sixties rendering style.
  29595. */
  29596. _this._cameraColorGradingTexture = null;
  29597. /**
  29598. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29599. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29600. * 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;
  29601. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29602. */
  29603. _this._cameraColorCurves = null;
  29604. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  29605. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  29606. /**
  29607. * AKA Occlusion Texture Intensity in other nomenclature.
  29608. */
  29609. _this._ambientTextureStrength = 1.0;
  29610. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  29611. /**
  29612. * AKA Diffuse Color in other nomenclature.
  29613. */
  29614. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  29615. /**
  29616. * AKA Specular Color in other nomenclature.
  29617. */
  29618. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  29619. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29620. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  29621. /**
  29622. * AKA Glossiness in other nomenclature.
  29623. */
  29624. _this._microSurface = 0.9;
  29625. /**
  29626. * source material index of refraction (IOR)' / 'destination material IOR.
  29627. */
  29628. _this._indexOfRefraction = 0.66;
  29629. /**
  29630. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  29631. */
  29632. _this._invertRefractionY = false;
  29633. /**
  29634. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  29635. * Materials half opaque for instance using refraction could benefit from this control.
  29636. */
  29637. _this._linkRefractionWithTransparency = false;
  29638. _this._useLightmapAsShadowmap = false;
  29639. /**
  29640. * In this mode, the emissive informtaion will always be added to the lighting once.
  29641. * A light for instance can be thought as emissive.
  29642. */
  29643. _this._useEmissiveAsIllumination = false;
  29644. /**
  29645. * Secifies that the alpha is coming form the albedo channel alpha channel.
  29646. */
  29647. _this._useAlphaFromAlbedoTexture = false;
  29648. /**
  29649. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  29650. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  29651. */
  29652. _this._useSpecularOverAlpha = true;
  29653. /**
  29654. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  29655. */
  29656. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  29657. /**
  29658. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  29659. */
  29660. _this._useRoughnessFromMetallicTextureAlpha = true;
  29661. /**
  29662. * Specifies if the metallic texture contains the roughness information in its green channel.
  29663. */
  29664. _this._useRoughnessFromMetallicTextureGreen = false;
  29665. /**
  29666. * Specifies if the metallic texture contains the metallness information in its blue channel.
  29667. */
  29668. _this._useMetallnessFromMetallicTextureBlue = false;
  29669. /**
  29670. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  29671. */
  29672. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  29673. /**
  29674. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  29675. */
  29676. _this._useAmbientInGrayScale = false;
  29677. /**
  29678. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  29679. * The material will try to infer what glossiness each pixel should be.
  29680. */
  29681. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  29682. /**
  29683. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  29684. * the creation of the material.
  29685. */
  29686. _this._useScalarInLinearSpace = false;
  29687. /**
  29688. * BJS is using an harcoded light falloff based on a manually sets up range.
  29689. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  29690. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  29691. */
  29692. _this._usePhysicalLightFalloff = true;
  29693. /**
  29694. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  29695. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  29696. */
  29697. _this._useRadianceOverAlpha = true;
  29698. /**
  29699. * Allows using the bump map in parallax mode.
  29700. */
  29701. _this._useParallax = false;
  29702. /**
  29703. * Allows using the bump map in parallax occlusion mode.
  29704. */
  29705. _this._useParallaxOcclusion = false;
  29706. /**
  29707. * Controls the scale bias of the parallax mode.
  29708. */
  29709. _this._parallaxScaleBias = 0.05;
  29710. /**
  29711. * If sets to true, disables all the lights affecting the material.
  29712. */
  29713. _this._disableLighting = false;
  29714. /**
  29715. * Number of Simultaneous lights allowed on the material.
  29716. */
  29717. _this._maxSimultaneousLights = 4;
  29718. /**
  29719. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29720. */
  29721. _this._invertNormalMapX = false;
  29722. /**
  29723. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29724. */
  29725. _this._invertNormalMapY = false;
  29726. /**
  29727. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  29728. */
  29729. _this._twoSidedLighting = false;
  29730. /**
  29731. * Defines the alpha limits in alpha test mode.
  29732. */
  29733. _this._alphaCutOff = 0.4;
  29734. /**
  29735. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  29736. */
  29737. _this._forceAlphaTest = false;
  29738. /**
  29739. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  29740. * in combination of post process in float or half float mode.
  29741. */
  29742. _this._ldrOutput = true;
  29743. _this._renderTargets = new BABYLON.SmartArray(16);
  29744. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29745. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29746. _this._tempColor = new BABYLON.Color3();
  29747. _this._defines = new PBRMaterialDefines();
  29748. _this._cachedDefines = new PBRMaterialDefines();
  29749. _this._myScene = null;
  29750. _this._myShadowGenerator = null;
  29751. _this._cachedDefines.BonesPerMesh = -1;
  29752. _this.getRenderTargetTextures = function () {
  29753. _this._renderTargets.reset();
  29754. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  29755. _this._renderTargets.push(_this._reflectionTexture);
  29756. }
  29757. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  29758. _this._renderTargets.push(_this._refractionTexture);
  29759. }
  29760. return _this._renderTargets;
  29761. };
  29762. return _this;
  29763. }
  29764. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  29765. get: function () {
  29766. return this._useLogarithmicDepth;
  29767. },
  29768. set: function (value) {
  29769. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29770. },
  29771. enumerable: true,
  29772. configurable: true
  29773. });
  29774. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  29775. if (this._linkRefractionWithTransparency) {
  29776. return false;
  29777. }
  29778. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  29779. };
  29780. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  29781. if (this._linkRefractionWithTransparency) {
  29782. return false;
  29783. }
  29784. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  29785. };
  29786. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  29787. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  29788. };
  29789. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  29790. return this._albedoTexture;
  29791. };
  29792. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29793. if (!mesh) {
  29794. return true;
  29795. }
  29796. if (this._defines.INSTANCES !== useInstances) {
  29797. return false;
  29798. }
  29799. return false;
  29800. };
  29801. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  29802. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  29803. };
  29804. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  29805. if (!useScalarInLinear) {
  29806. color.toLinearSpaceToRef(ref);
  29807. }
  29808. else {
  29809. ref.r = color.r;
  29810. ref.g = color.g;
  29811. ref.b = color.b;
  29812. }
  29813. };
  29814. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  29815. var lightIndex = 0;
  29816. var depthValuesAlreadySet = false;
  29817. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  29818. var light = _a[_i];
  29819. var useUbo = light._uniformBuffer.useUbo;
  29820. var scaledIntensity = light.getScaledIntensity();
  29821. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  29822. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29823. // GAMMA CORRECTION.
  29824. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  29825. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  29826. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  29827. if (defines["SPECULARTERM"]) {
  29828. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  29829. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  29830. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  29831. }
  29832. // Shadows
  29833. if (scene.shadowsEnabled) {
  29834. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  29835. }
  29836. light._uniformBuffer.update();
  29837. lightIndex++;
  29838. if (lightIndex === maxSimultaneousLights)
  29839. break;
  29840. }
  29841. };
  29842. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  29843. if (this.isFrozen) {
  29844. if (this._wasPreviouslyReady) {
  29845. return true;
  29846. }
  29847. }
  29848. var scene = this.getScene();
  29849. var engine = scene.getEngine();
  29850. var needUVs = false;
  29851. this._defines.reset();
  29852. if (scene.lightsEnabled && !this._disableLighting) {
  29853. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  29854. }
  29855. if (!this.checkReadyOnEveryCall) {
  29856. if (this._renderId === scene.getRenderId()) {
  29857. if (this._checkCache(scene, mesh, useInstances)) {
  29858. return true;
  29859. }
  29860. }
  29861. }
  29862. if (scene.texturesEnabled) {
  29863. if (scene.getEngine().getCaps().textureLOD) {
  29864. this._defines.LODBASEDMICROSFURACE = true;
  29865. }
  29866. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29867. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  29868. return false;
  29869. }
  29870. needUVs = true;
  29871. this._defines.ALBEDO = true;
  29872. }
  29873. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29874. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  29875. return false;
  29876. }
  29877. needUVs = true;
  29878. this._defines.AMBIENT = true;
  29879. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  29880. }
  29881. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29882. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  29883. return false;
  29884. }
  29885. needUVs = true;
  29886. this._defines.OPACITY = true;
  29887. if (this._opacityTexture.getAlphaFromRGB) {
  29888. this._defines.OPACITYRGB = true;
  29889. }
  29890. }
  29891. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  29892. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29893. if (!reflectionTexture.isReadyOrNotBlocking()) {
  29894. return false;
  29895. }
  29896. this._defines.REFLECTION = true;
  29897. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29898. this._defines.INVERTCUBICMAP = true;
  29899. }
  29900. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  29901. switch (reflectionTexture.coordinatesMode) {
  29902. case BABYLON.Texture.CUBIC_MODE:
  29903. case BABYLON.Texture.INVCUBIC_MODE:
  29904. this._defines.REFLECTIONMAP_CUBIC = true;
  29905. break;
  29906. case BABYLON.Texture.EXPLICIT_MODE:
  29907. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29908. break;
  29909. case BABYLON.Texture.PLANAR_MODE:
  29910. this._defines.REFLECTIONMAP_PLANAR = true;
  29911. break;
  29912. case BABYLON.Texture.PROJECTION_MODE:
  29913. this._defines.REFLECTIONMAP_PROJECTION = true;
  29914. break;
  29915. case BABYLON.Texture.SKYBOX_MODE:
  29916. this._defines.REFLECTIONMAP_SKYBOX = true;
  29917. break;
  29918. case BABYLON.Texture.SPHERICAL_MODE:
  29919. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29920. break;
  29921. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29922. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29923. break;
  29924. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29925. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29926. break;
  29927. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  29928. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  29929. break;
  29930. }
  29931. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  29932. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  29933. if (reflectionTexture.isPMREM) {
  29934. this._defines.USEPMREMREFLECTION = true;
  29935. }
  29936. }
  29937. }
  29938. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29939. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  29940. return false;
  29941. }
  29942. needUVs = true;
  29943. this._defines.LIGHTMAP = true;
  29944. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  29945. }
  29946. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29947. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  29948. return false;
  29949. }
  29950. needUVs = true;
  29951. this._defines.EMISSIVE = true;
  29952. }
  29953. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29954. if (this._metallicTexture) {
  29955. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  29956. return false;
  29957. }
  29958. needUVs = true;
  29959. this._defines.METALLICWORKFLOW = true;
  29960. this._defines.METALLICMAP = true;
  29961. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  29962. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  29963. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  29964. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  29965. }
  29966. else if (this._reflectivityTexture) {
  29967. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  29968. return false;
  29969. }
  29970. needUVs = true;
  29971. this._defines.REFLECTIVITY = true;
  29972. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  29973. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  29974. }
  29975. if (this._microSurfaceTexture) {
  29976. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  29977. return false;
  29978. }
  29979. needUVs = true;
  29980. this._defines.MICROSURFACEMAP = true;
  29981. }
  29982. }
  29983. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  29984. // Bump texure can not be none blocking.
  29985. if (!this._bumpTexture.isReady()) {
  29986. return false;
  29987. }
  29988. needUVs = true;
  29989. this._defines.BUMP = true;
  29990. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29991. this._defines.PARALLAX = true;
  29992. if (this._useParallaxOcclusion) {
  29993. this._defines.PARALLAXOCCLUSION = true;
  29994. }
  29995. }
  29996. if (this._invertNormalMapX) {
  29997. this._defines.INVERTNORMALMAPX = true;
  29998. }
  29999. if (this._invertNormalMapY) {
  30000. this._defines.INVERTNORMALMAPY = true;
  30001. }
  30002. if (scene._mirroredCameraPosition) {
  30003. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  30004. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  30005. }
  30006. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  30007. }
  30008. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30009. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30010. return false;
  30011. }
  30012. needUVs = true;
  30013. this._defines.REFRACTION = true;
  30014. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30015. if (this._linkRefractionWithTransparency) {
  30016. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  30017. }
  30018. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  30019. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  30020. if (this._refractionTexture.isPMREM) {
  30021. this._defines.USEPMREMREFRACTION = true;
  30022. }
  30023. }
  30024. }
  30025. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  30026. // Color Grading texure can not be none blocking.
  30027. if (!this._cameraColorGradingTexture.isReady()) {
  30028. return false;
  30029. }
  30030. this._defines.CAMERACOLORGRADING = true;
  30031. }
  30032. if (!this.backFaceCulling && this._twoSidedLighting) {
  30033. this._defines.TWOSIDEDLIGHTING = true;
  30034. }
  30035. }
  30036. this._defines.LDROUTPUT = this._ldrOutput;
  30037. // Effect
  30038. if (scene.clipPlane) {
  30039. this._defines.CLIPPLANE = true;
  30040. }
  30041. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  30042. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  30043. this._defines.ALPHATEST = true;
  30044. }
  30045. if (this._shouldUseAlphaFromAlbedoTexture()) {
  30046. this._defines.ALPHAFROMALBEDO = true;
  30047. }
  30048. if (this._useEmissiveAsIllumination) {
  30049. this._defines.EMISSIVEASILLUMINATION = true;
  30050. }
  30051. if (this.useLogarithmicDepth) {
  30052. this._defines.LOGARITHMICDEPTH = true;
  30053. }
  30054. if (this._cameraContrast != 1) {
  30055. this._defines.CAMERACONTRAST = true;
  30056. }
  30057. if (this._cameraExposure != 1) {
  30058. this._defines.CAMERATONEMAP = true;
  30059. }
  30060. if (this._cameraColorCurves) {
  30061. this._defines.CAMERACOLORCURVES = true;
  30062. }
  30063. // Point size
  30064. if (this.pointsCloud || scene.forcePointsCloud) {
  30065. this._defines.POINTSIZE = true;
  30066. }
  30067. // Fog
  30068. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30069. this._defines.FOG = true;
  30070. }
  30071. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30072. // Fresnel
  30073. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  30074. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30075. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30076. this._defines.OPACITYFRESNEL = true;
  30077. }
  30078. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30079. this._defines.EMISSIVEFRESNEL = true;
  30080. }
  30081. this._defines.FRESNEL = true;
  30082. }
  30083. }
  30084. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  30085. this._defines.SPECULAROVERALPHA = true;
  30086. }
  30087. if (this._usePhysicalLightFalloff) {
  30088. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  30089. }
  30090. if (this._useRadianceOverAlpha) {
  30091. this._defines.RADIANCEOVERALPHA = true;
  30092. }
  30093. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  30094. this._defines.METALLICWORKFLOW = true;
  30095. }
  30096. // Attribs
  30097. if (mesh) {
  30098. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30099. mesh.createNormals(true);
  30100. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  30101. }
  30102. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30103. this._defines.NORMAL = true;
  30104. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30105. this._defines.TANGENT = true;
  30106. }
  30107. }
  30108. if (needUVs) {
  30109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30110. this._defines.UV1 = true;
  30111. }
  30112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30113. this._defines.UV2 = true;
  30114. }
  30115. }
  30116. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30117. this._defines.VERTEXCOLOR = true;
  30118. if (mesh.hasVertexAlpha) {
  30119. this._defines.VERTEXALPHA = true;
  30120. }
  30121. }
  30122. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30123. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30124. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30125. }
  30126. // Instances
  30127. if (useInstances) {
  30128. this._defines.INSTANCES = true;
  30129. }
  30130. if (mesh.morphTargetManager) {
  30131. var manager = mesh.morphTargetManager;
  30132. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  30133. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  30134. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  30135. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  30136. }
  30137. }
  30138. // Get correct effect
  30139. if (!this._defines.isEqual(this._cachedDefines)) {
  30140. this._defines.cloneTo(this._cachedDefines);
  30141. scene.resetCachedMaterial();
  30142. // Fallbacks
  30143. var fallbacks = new BABYLON.EffectFallbacks();
  30144. if (this._defines.REFLECTION) {
  30145. fallbacks.addFallback(0, "REFLECTION");
  30146. }
  30147. if (this._defines.REFRACTION) {
  30148. fallbacks.addFallback(0, "REFRACTION");
  30149. }
  30150. if (this._defines.REFLECTIVITY) {
  30151. fallbacks.addFallback(0, "REFLECTIVITY");
  30152. }
  30153. if (this._defines.BUMP) {
  30154. fallbacks.addFallback(0, "BUMP");
  30155. }
  30156. if (this._defines.PARALLAX) {
  30157. fallbacks.addFallback(1, "PARALLAX");
  30158. }
  30159. if (this._defines.PARALLAXOCCLUSION) {
  30160. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30161. }
  30162. if (this._defines.SPECULAROVERALPHA) {
  30163. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30164. }
  30165. if (this._defines.FOG) {
  30166. fallbacks.addFallback(1, "FOG");
  30167. }
  30168. if (this._defines.POINTSIZE) {
  30169. fallbacks.addFallback(0, "POINTSIZE");
  30170. }
  30171. if (this._defines.LOGARITHMICDEPTH) {
  30172. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30173. }
  30174. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  30175. if (this._defines.SPECULARTERM) {
  30176. fallbacks.addFallback(0, "SPECULARTERM");
  30177. }
  30178. if (this._defines.OPACITYFRESNEL) {
  30179. fallbacks.addFallback(1, "OPACITYFRESNEL");
  30180. }
  30181. if (this._defines.EMISSIVEFRESNEL) {
  30182. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  30183. }
  30184. if (this._defines.FRESNEL) {
  30185. fallbacks.addFallback(3, "FRESNEL");
  30186. }
  30187. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  30188. fallbacks.addCPUSkinningFallback(0, mesh);
  30189. }
  30190. //Attributes
  30191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30192. if (this._defines.NORMAL) {
  30193. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30194. }
  30195. if (this._defines.TANGENT) {
  30196. attribs.push(BABYLON.VertexBuffer.TangentKind);
  30197. }
  30198. if (this._defines.UV1) {
  30199. attribs.push(BABYLON.VertexBuffer.UVKind);
  30200. }
  30201. if (this._defines.UV2) {
  30202. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30203. }
  30204. if (this._defines.VERTEXCOLOR) {
  30205. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30206. }
  30207. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30208. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30209. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  30210. // Legacy browser patch
  30211. var join = this._defines.toString();
  30212. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  30213. "vFogInfos", "vFogColor", "pointSize",
  30214. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30215. "mBones",
  30216. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30217. "depthValues",
  30218. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  30219. "vLightingIntensity",
  30220. "logarithmicDepthConstant",
  30221. "vSphericalX", "vSphericalY", "vSphericalZ",
  30222. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  30223. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  30224. "vMicrosurfaceTextureLods",
  30225. "vCameraInfos"
  30226. ];
  30227. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30228. var uniformBuffers = ["Material", "Scene"];
  30229. if (this._defines.CAMERACOLORCURVES) {
  30230. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30231. }
  30232. if (this._defines.CAMERACOLORGRADING) {
  30233. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30234. }
  30235. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30236. uniformsNames: uniforms,
  30237. uniformBuffersNames: uniformBuffers,
  30238. samplers: samplers,
  30239. defines: this._defines,
  30240. maxSimultaneousLights: this._maxSimultaneousLights
  30241. });
  30242. var onCompiled = function (effect) {
  30243. if (this.onCompiled) {
  30244. this.onCompiled(effect);
  30245. }
  30246. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  30247. }.bind(this);
  30248. this._effect = scene.getEngine().createEffect("pbr", {
  30249. attributes: attribs,
  30250. uniformsNames: uniforms,
  30251. uniformBuffersNames: uniformBuffers,
  30252. samplers: samplers,
  30253. defines: join,
  30254. fallbacks: fallbacks,
  30255. onCompiled: onCompiled,
  30256. onError: this.onError,
  30257. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  30258. }, engine);
  30259. this.buildUniformLayout();
  30260. }
  30261. if (!this._effect.isReady()) {
  30262. return false;
  30263. }
  30264. this._renderId = scene.getRenderId();
  30265. this._wasPreviouslyReady = true;
  30266. return true;
  30267. };
  30268. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  30269. // Order is important !
  30270. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  30271. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  30272. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30273. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30274. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30275. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  30276. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  30277. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30278. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30279. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30280. this._uniformBuffer.addUniform("albedoMatrix", 16);
  30281. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30282. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30283. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30284. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30285. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  30286. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  30287. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30288. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30289. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30290. this._uniformBuffer.addUniform("vReflectionColor", 3);
  30291. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  30292. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  30293. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  30294. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  30295. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30296. this._uniformBuffer.addUniform("opacityParts", 4);
  30297. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30298. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30299. this._uniformBuffer.addUniform("pointSize", 1);
  30300. this._uniformBuffer.create();
  30301. };
  30302. PBRBaseMaterial.prototype.unbind = function () {
  30303. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30304. this._uniformBuffer.setTexture("reflection2DSampler", null);
  30305. }
  30306. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30307. this._uniformBuffer.setTexture("refraction2DSampler", null);
  30308. }
  30309. _super.prototype.unbind.call(this);
  30310. };
  30311. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30312. this._effect.setMatrix("world", world);
  30313. };
  30314. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  30315. this._myScene = this.getScene();
  30316. var effect = this._effect;
  30317. // Matrices
  30318. this.bindOnlyWorldMatrix(world);
  30319. // Bones
  30320. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30321. if (this._myScene.getCachedMaterial() !== this) {
  30322. this._uniformBuffer.bindToEffect(effect, "Material");
  30323. this.bindViewProjection(effect);
  30324. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30325. // Fresnel
  30326. if (BABYLON.StandardMaterial.FresnelEnabled) {
  30327. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  30328. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  30329. }
  30330. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  30331. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  30332. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  30333. }
  30334. }
  30335. // Texture uniforms
  30336. if (this._myScene.texturesEnabled) {
  30337. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30338. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  30339. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  30340. }
  30341. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30342. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  30343. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  30344. }
  30345. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30346. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30347. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  30348. }
  30349. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  30350. ;
  30351. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30352. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  30353. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  30354. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  30355. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  30356. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  30357. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  30358. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  30359. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  30360. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  30361. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  30362. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  30363. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  30364. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  30365. }
  30366. }
  30367. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30368. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30369. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  30370. }
  30371. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30372. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30373. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  30374. }
  30375. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30376. if (this._metallicTexture) {
  30377. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  30378. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  30379. }
  30380. else if (this._reflectivityTexture) {
  30381. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  30382. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  30383. }
  30384. if (this._microSurfaceTexture) {
  30385. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  30386. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  30387. }
  30388. }
  30389. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30390. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  30391. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  30392. }
  30393. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30394. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  30395. var depth = 1.0;
  30396. if (!this._refractionTexture.isCube) {
  30397. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30398. if (this._refractionTexture.depth) {
  30399. depth = this._refractionTexture.depth;
  30400. }
  30401. }
  30402. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  30403. }
  30404. if ((reflectionTexture || this._refractionTexture)) {
  30405. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  30406. }
  30407. }
  30408. // Point size
  30409. if (this.pointsCloud) {
  30410. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30411. }
  30412. // Colors
  30413. if (this._defines.METALLICWORKFLOW) {
  30414. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  30415. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  30416. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  30417. }
  30418. else {
  30419. // GAMMA CORRECTION.
  30420. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  30421. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  30422. }
  30423. // GAMMA CORRECTION.
  30424. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  30425. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  30426. // GAMMA CORRECTION.
  30427. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  30428. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  30429. // GAMMA CORRECTION.
  30430. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  30431. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  30432. // Misc
  30433. this._lightingInfos.x = this._directIntensity;
  30434. this._lightingInfos.y = this._emissiveIntensity;
  30435. this._lightingInfos.z = this._environmentIntensity;
  30436. this._lightingInfos.w = this._specularIntensity;
  30437. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  30438. }
  30439. // Textures
  30440. if (this._myScene.texturesEnabled) {
  30441. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  30442. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  30443. }
  30444. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  30445. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  30446. }
  30447. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  30448. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  30449. }
  30450. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  30451. if (reflectionTexture.isCube) {
  30452. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  30453. }
  30454. else {
  30455. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  30456. }
  30457. }
  30458. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  30459. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  30460. }
  30461. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  30462. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  30463. }
  30464. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  30465. if (this._metallicTexture) {
  30466. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  30467. }
  30468. else if (this._reflectivityTexture) {
  30469. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  30470. }
  30471. if (this._microSurfaceTexture) {
  30472. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  30473. }
  30474. }
  30475. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  30476. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  30477. }
  30478. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  30479. if (this._refractionTexture.isCube) {
  30480. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  30481. }
  30482. else {
  30483. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  30484. }
  30485. }
  30486. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  30487. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  30488. }
  30489. }
  30490. // Clip plane
  30491. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  30492. // Colors
  30493. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  30494. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  30495. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30496. }
  30497. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  30498. // Lights
  30499. if (this._myScene.lightsEnabled && !this._disableLighting) {
  30500. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  30501. }
  30502. // View
  30503. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  30504. this.bindView(effect);
  30505. }
  30506. // Fog
  30507. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  30508. // Morph targets
  30509. if (this._defines.NUM_MORPH_INFLUENCERS) {
  30510. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  30511. }
  30512. this._cameraInfos.x = this._cameraExposure;
  30513. this._cameraInfos.y = this._cameraContrast;
  30514. effect.setVector4("vCameraInfos", this._cameraInfos);
  30515. if (this._cameraColorCurves) {
  30516. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  30517. }
  30518. // Log. depth
  30519. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  30520. }
  30521. this._uniformBuffer.update();
  30522. this._afterBind(mesh);
  30523. this._myScene = null;
  30524. };
  30525. PBRBaseMaterial.prototype.getAnimatables = function () {
  30526. var results = [];
  30527. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  30528. results.push(this._albedoTexture);
  30529. }
  30530. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30531. results.push(this._ambientTexture);
  30532. }
  30533. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30534. results.push(this._opacityTexture);
  30535. }
  30536. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30537. results.push(this._reflectionTexture);
  30538. }
  30539. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30540. results.push(this._emissiveTexture);
  30541. }
  30542. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  30543. results.push(this._metallicTexture);
  30544. }
  30545. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  30546. results.push(this._reflectivityTexture);
  30547. }
  30548. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30549. results.push(this._bumpTexture);
  30550. }
  30551. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30552. results.push(this._lightmapTexture);
  30553. }
  30554. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30555. results.push(this._refractionTexture);
  30556. }
  30557. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  30558. results.push(this._cameraColorGradingTexture);
  30559. }
  30560. return results;
  30561. };
  30562. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30563. if (forceDisposeTextures) {
  30564. if (this._albedoTexture) {
  30565. this._albedoTexture.dispose();
  30566. }
  30567. if (this._ambientTexture) {
  30568. this._ambientTexture.dispose();
  30569. }
  30570. if (this._opacityTexture) {
  30571. this._opacityTexture.dispose();
  30572. }
  30573. if (this._reflectionTexture) {
  30574. this._reflectionTexture.dispose();
  30575. }
  30576. if (this._emissiveTexture) {
  30577. this._emissiveTexture.dispose();
  30578. }
  30579. if (this._metallicTexture) {
  30580. this._metallicTexture.dispose();
  30581. }
  30582. if (this._reflectivityTexture) {
  30583. this._reflectivityTexture.dispose();
  30584. }
  30585. if (this._bumpTexture) {
  30586. this._bumpTexture.dispose();
  30587. }
  30588. if (this._lightmapTexture) {
  30589. this._lightmapTexture.dispose();
  30590. }
  30591. if (this._refractionTexture) {
  30592. this._refractionTexture.dispose();
  30593. }
  30594. if (this._cameraColorGradingTexture) {
  30595. this._cameraColorGradingTexture.dispose();
  30596. }
  30597. }
  30598. this._renderTargets.dispose();
  30599. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30600. };
  30601. return PBRBaseMaterial;
  30602. }(BABYLON.Material));
  30603. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  30604. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  30605. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  30606. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  30607. __decorate([
  30608. BABYLON.serialize()
  30609. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  30610. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  30611. })(BABYLON || (BABYLON = {}));
  30612. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  30613. var BABYLON;
  30614. (function (BABYLON) {
  30615. var Internals;
  30616. (function (Internals) {
  30617. /**
  30618. * The Physically based simple base material of BJS.
  30619. *
  30620. * This enables better naming and convention enforcements on top of the pbrMaterial.
  30621. * It is used as the base class for both the specGloss and metalRough conventions.
  30622. */
  30623. var PBRBaseSimpleMaterial = (function (_super) {
  30624. __extends(PBRBaseSimpleMaterial, _super);
  30625. /**
  30626. * Instantiates a new PBRMaterial instance.
  30627. *
  30628. * @param name The material name
  30629. * @param scene The scene the material will be use in.
  30630. */
  30631. function PBRBaseSimpleMaterial(name, scene) {
  30632. var _this = _super.call(this, name, scene) || this;
  30633. /**
  30634. * Number of Simultaneous lights allowed on the material.
  30635. */
  30636. _this.maxSimultaneousLights = 4;
  30637. /**
  30638. * If sets to true, disables all the lights affecting the material.
  30639. */
  30640. _this.disableLighting = false;
  30641. /**
  30642. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30643. */
  30644. _this.invertNormalMapX = false;
  30645. /**
  30646. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30647. */
  30648. _this.invertNormalMapY = false;
  30649. /**
  30650. * Emissivie color used to self-illuminate the model.
  30651. */
  30652. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30653. /**
  30654. * Occlusion Channel Strenght.
  30655. */
  30656. _this.occlusionStrength = 1.0;
  30657. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30658. _this._useEmissiveAsIllumination = true;
  30659. _this._useAmbientInGrayScale = true;
  30660. _this._useScalarInLinearSpace = true;
  30661. return _this;
  30662. }
  30663. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  30664. /**
  30665. * Gets the current transparency mode.
  30666. */
  30667. get: function () {
  30668. return this._transparencyMode;
  30669. },
  30670. /**
  30671. * Sets the transparency mode of the material.
  30672. */
  30673. set: function (value) {
  30674. this._transparencyMode = value;
  30675. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  30676. this._forceAlphaTest = true;
  30677. }
  30678. else {
  30679. this._forceAlphaTest = false;
  30680. }
  30681. },
  30682. enumerable: true,
  30683. configurable: true
  30684. });
  30685. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  30686. /**
  30687. * Gets the current double sided mode.
  30688. */
  30689. get: function () {
  30690. return this._twoSidedLighting;
  30691. },
  30692. /**
  30693. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30694. */
  30695. set: function (value) {
  30696. this._twoSidedLighting = value;
  30697. this.backFaceCulling = !value;
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. /**
  30703. * Specifies wether or not the alpha value of the albedo texture should be used.
  30704. */
  30705. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  30706. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  30707. };
  30708. /**
  30709. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  30710. */
  30711. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  30712. if (this._linkRefractionWithTransparency) {
  30713. return false;
  30714. }
  30715. return (this.alpha < 1.0) ||
  30716. (this._shouldUseAlphaFromAlbedoTexture() &&
  30717. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  30718. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  30719. };
  30720. /**
  30721. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  30722. */
  30723. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  30724. if (this._linkRefractionWithTransparency) {
  30725. return false;
  30726. }
  30727. return this._shouldUseAlphaFromAlbedoTexture() &&
  30728. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  30729. };
  30730. return PBRBaseSimpleMaterial;
  30731. }(BABYLON.PBRBaseMaterial));
  30732. __decorate([
  30733. BABYLON.serialize(),
  30734. BABYLON.expandToProperty(null)
  30735. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  30736. __decorate([
  30737. BABYLON.serialize(),
  30738. BABYLON.expandToProperty(null)
  30739. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  30740. __decorate([
  30741. BABYLON.serializeAsTexture(),
  30742. BABYLON.expandToProperty(null, "_reflectionTexture")
  30743. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  30744. __decorate([
  30745. BABYLON.serialize(),
  30746. BABYLON.expandToProperty(null)
  30747. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  30748. __decorate([
  30749. BABYLON.serialize(),
  30750. BABYLON.expandToProperty(null)
  30751. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  30752. __decorate([
  30753. BABYLON.serializeAsTexture(),
  30754. BABYLON.expandToProperty(null, "_bumpTexture")
  30755. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  30756. __decorate([
  30757. BABYLON.serializeAsColor3("emissive"),
  30758. BABYLON.expandToProperty(null)
  30759. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  30760. __decorate([
  30761. BABYLON.serializeAsTexture(),
  30762. BABYLON.expandToProperty(null)
  30763. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  30764. __decorate([
  30765. BABYLON.serialize(),
  30766. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  30767. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  30768. __decorate([
  30769. BABYLON.serializeAsTexture(),
  30770. BABYLON.expandToProperty(null, "_ambientTexture")
  30771. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  30772. __decorate([
  30773. BABYLON.serialize(),
  30774. BABYLON.expandToProperty(null, "_alphaCutOff")
  30775. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  30776. __decorate([
  30777. BABYLON.serialize()
  30778. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  30779. __decorate([
  30780. BABYLON.serialize()
  30781. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  30782. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  30783. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  30784. })(BABYLON || (BABYLON = {}));
  30785. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  30786. var BABYLON;
  30787. (function (BABYLON) {
  30788. /**
  30789. * The Physically based material of BJS.
  30790. *
  30791. * This offers the main features of a standard PBR material.
  30792. * For more information, please refer to the documentation :
  30793. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  30794. */
  30795. var PBRMaterial = (function (_super) {
  30796. __extends(PBRMaterial, _super);
  30797. /**
  30798. * Instantiates a new PBRMaterial instance.
  30799. *
  30800. * @param name The material name
  30801. * @param scene The scene the material will be use in.
  30802. */
  30803. function PBRMaterial(name, scene) {
  30804. var _this = _super.call(this, name, scene) || this;
  30805. /**
  30806. * Intensity of the direct lights e.g. the four lights available in your scene.
  30807. * This impacts both the direct diffuse and specular highlights.
  30808. */
  30809. _this.directIntensity = 1.0;
  30810. /**
  30811. * Intensity of the emissive part of the material.
  30812. * This helps controlling the emissive effect without modifying the emissive color.
  30813. */
  30814. _this.emissiveIntensity = 1.0;
  30815. /**
  30816. * Intensity of the environment e.g. how much the environment will light the object
  30817. * either through harmonics for rough material or through the refelction for shiny ones.
  30818. */
  30819. _this.environmentIntensity = 1.0;
  30820. /**
  30821. * This is a special control allowing the reduction of the specular highlights coming from the
  30822. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  30823. */
  30824. _this.specularIntensity = 1.0;
  30825. /**
  30826. * Debug Control allowing disabling the bump map on this material.
  30827. */
  30828. _this.disableBumpMap = false;
  30829. /**
  30830. * The camera exposure used on this material.
  30831. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30832. * This corresponds to a photographic exposure.
  30833. */
  30834. _this.cameraExposure = 1.0;
  30835. /**
  30836. * The camera contrast used on this material.
  30837. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  30838. */
  30839. _this.cameraContrast = 1.0;
  30840. /**
  30841. * Color Grading 2D Lookup Texture.
  30842. * This allows special effects like sepia, black and white to sixties rendering style.
  30843. */
  30844. _this.cameraColorGradingTexture = null;
  30845. /**
  30846. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30847. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30848. * 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;
  30849. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30850. */
  30851. _this.cameraColorCurves = null;
  30852. /**
  30853. * AKA Occlusion Texture Intensity in other nomenclature.
  30854. */
  30855. _this.ambientTextureStrength = 1.0;
  30856. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30857. /**
  30858. * AKA Diffuse Color in other nomenclature.
  30859. */
  30860. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  30861. /**
  30862. * AKA Specular Color in other nomenclature.
  30863. */
  30864. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  30865. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  30866. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30867. /**
  30868. * AKA Glossiness in other nomenclature.
  30869. */
  30870. _this.microSurface = 0.9;
  30871. /**
  30872. * source material index of refraction (IOR)' / 'destination material IOR.
  30873. */
  30874. _this.indexOfRefraction = 0.66;
  30875. /**
  30876. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  30877. */
  30878. _this.invertRefractionY = false;
  30879. /**
  30880. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  30881. * Materials half opaque for instance using refraction could benefit from this control.
  30882. */
  30883. _this.linkRefractionWithTransparency = false;
  30884. _this.useLightmapAsShadowmap = false;
  30885. /**
  30886. * In this mode, the emissive informtaion will always be added to the lighting once.
  30887. * A light for instance can be thought as emissive.
  30888. */
  30889. _this.useEmissiveAsIllumination = false;
  30890. /**
  30891. * Secifies that the alpha is coming form the albedo channel alpha channel.
  30892. */
  30893. _this.useAlphaFromAlbedoTexture = false;
  30894. /**
  30895. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  30896. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  30897. */
  30898. _this.useSpecularOverAlpha = true;
  30899. /**
  30900. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  30901. */
  30902. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  30903. /**
  30904. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  30905. */
  30906. _this.useRoughnessFromMetallicTextureAlpha = true;
  30907. /**
  30908. * Specifies if the metallic texture contains the roughness information in its green channel.
  30909. */
  30910. _this.useRoughnessFromMetallicTextureGreen = false;
  30911. /**
  30912. * Specifies if the metallic texture contains the metallness information in its blue channel.
  30913. */
  30914. _this.useMetallnessFromMetallicTextureBlue = false;
  30915. /**
  30916. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  30917. */
  30918. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  30919. /**
  30920. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  30921. */
  30922. _this.useAmbientInGrayScale = false;
  30923. /**
  30924. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  30925. * The material will try to infer what glossiness each pixel should be.
  30926. */
  30927. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  30928. /**
  30929. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  30930. * the creation of the material.
  30931. */
  30932. _this.useScalarInLinearSpace = false;
  30933. /**
  30934. * BJS is using an harcoded light falloff based on a manually sets up range.
  30935. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  30936. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  30937. */
  30938. _this.usePhysicalLightFalloff = true;
  30939. /**
  30940. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  30941. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  30942. */
  30943. _this.useRadianceOverAlpha = true;
  30944. /**
  30945. * Allows using the bump map in parallax mode.
  30946. */
  30947. _this.useParallax = false;
  30948. /**
  30949. * Allows using the bump map in parallax occlusion mode.
  30950. */
  30951. _this.useParallaxOcclusion = false;
  30952. /**
  30953. * Controls the scale bias of the parallax mode.
  30954. */
  30955. _this.parallaxScaleBias = 0.05;
  30956. /**
  30957. * If sets to true, disables all the lights affecting the material.
  30958. */
  30959. _this.disableLighting = false;
  30960. /**
  30961. * Number of Simultaneous lights allowed on the material.
  30962. */
  30963. _this.maxSimultaneousLights = 4;
  30964. /**
  30965. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30966. */
  30967. _this.invertNormalMapX = false;
  30968. /**
  30969. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30970. */
  30971. _this.invertNormalMapY = false;
  30972. /**
  30973. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30974. */
  30975. _this.twoSidedLighting = false;
  30976. return _this;
  30977. }
  30978. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  30979. /**
  30980. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  30981. */
  30982. get: function () {
  30983. return this._PBRMATERIAL_OPAQUE;
  30984. },
  30985. enumerable: true,
  30986. configurable: true
  30987. });
  30988. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  30989. /**
  30990. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  30991. */
  30992. get: function () {
  30993. return this._PBRMATERIAL_ALPHATEST;
  30994. },
  30995. enumerable: true,
  30996. configurable: true
  30997. });
  30998. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  30999. /**
  31000. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31001. */
  31002. get: function () {
  31003. return this._PBRMATERIAL_ALPHABLEND;
  31004. },
  31005. enumerable: true,
  31006. configurable: true
  31007. });
  31008. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  31009. /**
  31010. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  31011. * They are also discarded below the alpha cutoff threshold to improve performances.
  31012. */
  31013. get: function () {
  31014. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. PBRMaterial.prototype.getClassName = function () {
  31020. return "PBRMaterial";
  31021. };
  31022. PBRMaterial.prototype.clone = function (name) {
  31023. var _this = this;
  31024. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  31025. };
  31026. PBRMaterial.prototype.serialize = function () {
  31027. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31028. serializationObject.customType = "BABYLON.PBRMaterial";
  31029. return serializationObject;
  31030. };
  31031. // Statics
  31032. PBRMaterial.Parse = function (source, scene, rootUrl) {
  31033. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  31034. };
  31035. return PBRMaterial;
  31036. }(BABYLON.PBRBaseMaterial));
  31037. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  31038. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  31039. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  31040. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  31041. __decorate([
  31042. BABYLON.serialize(),
  31043. BABYLON.expandToProperty(null)
  31044. ], PBRMaterial.prototype, "directIntensity", void 0);
  31045. __decorate([
  31046. BABYLON.serialize(),
  31047. BABYLON.expandToProperty(null)
  31048. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  31049. __decorate([
  31050. BABYLON.serialize(),
  31051. BABYLON.expandToProperty(null)
  31052. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  31053. __decorate([
  31054. BABYLON.serialize(),
  31055. BABYLON.expandToProperty(null)
  31056. ], PBRMaterial.prototype, "specularIntensity", void 0);
  31057. __decorate([
  31058. BABYLON.serialize(),
  31059. BABYLON.expandToProperty(null)
  31060. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  31061. __decorate([
  31062. BABYLON.serialize(),
  31063. BABYLON.expandToProperty(null)
  31064. ], PBRMaterial.prototype, "cameraExposure", void 0);
  31065. __decorate([
  31066. BABYLON.serialize(),
  31067. BABYLON.expandToProperty(null)
  31068. ], PBRMaterial.prototype, "cameraContrast", void 0);
  31069. __decorate([
  31070. BABYLON.serializeAsTexture(),
  31071. BABYLON.expandToProperty(null)
  31072. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  31073. __decorate([
  31074. BABYLON.serializeAsColorCurves(),
  31075. BABYLON.expandToProperty(null)
  31076. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  31077. __decorate([
  31078. BABYLON.serializeAsTexture(),
  31079. BABYLON.expandToProperty(null)
  31080. ], PBRMaterial.prototype, "albedoTexture", void 0);
  31081. __decorate([
  31082. BABYLON.serializeAsTexture(),
  31083. BABYLON.expandToProperty(null)
  31084. ], PBRMaterial.prototype, "ambientTexture", void 0);
  31085. __decorate([
  31086. BABYLON.serialize(),
  31087. BABYLON.expandToProperty(null)
  31088. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  31089. __decorate([
  31090. BABYLON.serializeAsTexture(),
  31091. BABYLON.expandToProperty(null)
  31092. ], PBRMaterial.prototype, "opacityTexture", void 0);
  31093. __decorate([
  31094. BABYLON.serializeAsTexture(),
  31095. BABYLON.expandToProperty(null)
  31096. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  31097. __decorate([
  31098. BABYLON.serializeAsTexture(),
  31099. BABYLON.expandToProperty(null)
  31100. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  31101. __decorate([
  31102. BABYLON.serializeAsTexture(),
  31103. BABYLON.expandToProperty(null)
  31104. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  31105. __decorate([
  31106. BABYLON.serializeAsTexture(),
  31107. BABYLON.expandToProperty(null)
  31108. ], PBRMaterial.prototype, "metallicTexture", void 0);
  31109. __decorate([
  31110. BABYLON.serialize(),
  31111. BABYLON.expandToProperty(null)
  31112. ], PBRMaterial.prototype, "metallic", void 0);
  31113. __decorate([
  31114. BABYLON.serialize(),
  31115. BABYLON.expandToProperty(null)
  31116. ], PBRMaterial.prototype, "roughness", void 0);
  31117. __decorate([
  31118. BABYLON.serializeAsTexture(),
  31119. BABYLON.expandToProperty(null)
  31120. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  31121. __decorate([
  31122. BABYLON.serializeAsTexture(),
  31123. BABYLON.expandToProperty(null)
  31124. ], PBRMaterial.prototype, "bumpTexture", void 0);
  31125. __decorate([
  31126. BABYLON.serializeAsTexture(),
  31127. BABYLON.expandToProperty(null)
  31128. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  31129. __decorate([
  31130. BABYLON.serializeAsTexture(),
  31131. BABYLON.expandToProperty(null)
  31132. ], PBRMaterial.prototype, "refractionTexture", void 0);
  31133. __decorate([
  31134. BABYLON.serializeAsColor3("ambient"),
  31135. BABYLON.expandToProperty(null)
  31136. ], PBRMaterial.prototype, "ambientColor", void 0);
  31137. __decorate([
  31138. BABYLON.serializeAsColor3("albedo"),
  31139. BABYLON.expandToProperty(null)
  31140. ], PBRMaterial.prototype, "albedoColor", void 0);
  31141. __decorate([
  31142. BABYLON.serializeAsColor3("reflectivity"),
  31143. BABYLON.expandToProperty(null)
  31144. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  31145. __decorate([
  31146. BABYLON.serializeAsColor3("reflection"),
  31147. BABYLON.expandToProperty(null)
  31148. ], PBRMaterial.prototype, "reflectionColor", void 0);
  31149. __decorate([
  31150. BABYLON.serializeAsColor3("emissive"),
  31151. BABYLON.expandToProperty(null)
  31152. ], PBRMaterial.prototype, "emissiveColor", void 0);
  31153. __decorate([
  31154. BABYLON.serialize(),
  31155. BABYLON.expandToProperty(null)
  31156. ], PBRMaterial.prototype, "microSurface", void 0);
  31157. __decorate([
  31158. BABYLON.serialize(),
  31159. BABYLON.expandToProperty(null)
  31160. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  31161. __decorate([
  31162. BABYLON.serialize(),
  31163. BABYLON.expandToProperty(null)
  31164. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  31165. __decorate([
  31166. BABYLON.serializeAsFresnelParameters(),
  31167. BABYLON.expandToProperty(null)
  31168. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  31169. __decorate([
  31170. BABYLON.serializeAsFresnelParameters(),
  31171. BABYLON.expandToProperty(null)
  31172. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  31173. __decorate([
  31174. BABYLON.serialize(),
  31175. BABYLON.expandToProperty(null)
  31176. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  31177. __decorate([
  31178. BABYLON.serialize(),
  31179. BABYLON.expandToProperty(null)
  31180. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31181. __decorate([
  31182. BABYLON.serialize(),
  31183. BABYLON.expandToProperty(null)
  31184. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31185. __decorate([
  31186. BABYLON.serialize(),
  31187. BABYLON.expandToProperty(null)
  31188. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  31189. __decorate([
  31190. BABYLON.serialize(),
  31191. BABYLON.expandToProperty(null)
  31192. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  31193. __decorate([
  31194. BABYLON.serialize(),
  31195. BABYLON.expandToProperty(null)
  31196. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  31197. __decorate([
  31198. BABYLON.serialize(),
  31199. BABYLON.expandToProperty(null)
  31200. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  31201. __decorate([
  31202. BABYLON.serialize(),
  31203. BABYLON.expandToProperty(null)
  31204. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  31205. __decorate([
  31206. BABYLON.serialize(),
  31207. BABYLON.expandToProperty(null)
  31208. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  31209. __decorate([
  31210. BABYLON.serialize(),
  31211. BABYLON.expandToProperty(null)
  31212. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  31213. __decorate([
  31214. BABYLON.serialize(),
  31215. BABYLON.expandToProperty(null)
  31216. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  31217. __decorate([
  31218. BABYLON.serialize(),
  31219. BABYLON.expandToProperty(null)
  31220. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  31221. __decorate([
  31222. BABYLON.serialize(),
  31223. BABYLON.expandToProperty(null)
  31224. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  31225. __decorate([
  31226. BABYLON.serialize(),
  31227. BABYLON.expandToProperty(null)
  31228. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  31229. __decorate([
  31230. BABYLON.serialize(),
  31231. BABYLON.expandToProperty(null)
  31232. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  31233. __decorate([
  31234. BABYLON.serialize(),
  31235. BABYLON.expandToProperty(null)
  31236. ], PBRMaterial.prototype, "useParallax", void 0);
  31237. __decorate([
  31238. BABYLON.serialize(),
  31239. BABYLON.expandToProperty(null)
  31240. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  31241. __decorate([
  31242. BABYLON.serialize(),
  31243. BABYLON.expandToProperty(null)
  31244. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  31245. __decorate([
  31246. BABYLON.serialize(),
  31247. BABYLON.expandToProperty(null)
  31248. ], PBRMaterial.prototype, "disableLighting", void 0);
  31249. __decorate([
  31250. BABYLON.serialize(),
  31251. BABYLON.expandToProperty(null)
  31252. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  31253. __decorate([
  31254. BABYLON.serialize(),
  31255. BABYLON.expandToProperty(null)
  31256. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  31257. __decorate([
  31258. BABYLON.serialize(),
  31259. BABYLON.expandToProperty(null)
  31260. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  31261. __decorate([
  31262. BABYLON.serialize(),
  31263. BABYLON.expandToProperty(null)
  31264. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  31265. BABYLON.PBRMaterial = PBRMaterial;
  31266. })(BABYLON || (BABYLON = {}));
  31267. //# sourceMappingURL=babylon.pbrMaterial.js.map
  31268. var BABYLON;
  31269. (function (BABYLON) {
  31270. /**
  31271. * The PBR material of BJS following the metal roughness convention.
  31272. *
  31273. * This fits to the define PBR convention in the GLTF definition:
  31274. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  31275. */
  31276. var PBRMetallicRoughnessMaterial = (function (_super) {
  31277. __extends(PBRMetallicRoughnessMaterial, _super);
  31278. /**
  31279. * Instantiates a new PBRMetalRoughnessMaterial instance.
  31280. *
  31281. * @param name The material name
  31282. * @param scene The scene the material will be use in.
  31283. */
  31284. function PBRMetallicRoughnessMaterial(name, scene) {
  31285. var _this = _super.call(this, name, scene) || this;
  31286. _this._useRoughnessFromMetallicTextureGreen = true;
  31287. _this._useMetallnessFromMetallicTextureBlue = true;
  31288. return _this;
  31289. }
  31290. /**
  31291. * Return the currrent class name of the material.
  31292. */
  31293. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  31294. return "PBRMetallicRoughnessMaterial";
  31295. };
  31296. /**
  31297. * Serialize the material to a parsable JSON object.
  31298. */
  31299. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  31300. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31301. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  31302. return serializationObject;
  31303. };
  31304. /**
  31305. * Parses a JSON object correponding to the serialize function.
  31306. */
  31307. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  31308. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  31309. };
  31310. return PBRMetallicRoughnessMaterial;
  31311. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31312. __decorate([
  31313. BABYLON.serializeAsTexture(),
  31314. BABYLON.expandToProperty(null, "_albedoColor")
  31315. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  31316. __decorate([
  31317. BABYLON.serializeAsTexture(),
  31318. BABYLON.expandToProperty(null, "_albedoTexture")
  31319. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  31320. __decorate([
  31321. BABYLON.serialize(),
  31322. BABYLON.expandToProperty(null)
  31323. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  31324. __decorate([
  31325. BABYLON.serialize(),
  31326. BABYLON.expandToProperty(null)
  31327. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  31328. __decorate([
  31329. BABYLON.serializeAsTexture(),
  31330. BABYLON.expandToProperty(null, "_metallicTexture")
  31331. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  31332. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  31333. })(BABYLON || (BABYLON = {}));
  31334. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  31335. var BABYLON;
  31336. (function (BABYLON) {
  31337. /**
  31338. * The PBR material of BJS following the specular glossiness convention.
  31339. *
  31340. * This fits to the define PBR convention in the GLTF definition:
  31341. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  31342. */
  31343. var PBRSpecularGlossinessMaterial = (function (_super) {
  31344. __extends(PBRSpecularGlossinessMaterial, _super);
  31345. /**
  31346. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  31347. *
  31348. * @param name The material name
  31349. * @param scene The scene the material will be use in.
  31350. */
  31351. function PBRSpecularGlossinessMaterial(name, scene) {
  31352. var _this = _super.call(this, name, scene) || this;
  31353. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  31354. return _this;
  31355. }
  31356. /**
  31357. * Return the currrent class name of the material.
  31358. */
  31359. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  31360. return "PBRSpecularGlossinessMaterial";
  31361. };
  31362. /**
  31363. * Serialize the material to a parsable JSON object.
  31364. */
  31365. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  31366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31367. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  31368. return serializationObject;
  31369. };
  31370. /**
  31371. * Parses a JSON object correponding to the serialize function.
  31372. */
  31373. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  31374. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  31375. };
  31376. return PBRSpecularGlossinessMaterial;
  31377. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  31378. __decorate([
  31379. BABYLON.serializeAsColor3(),
  31380. BABYLON.expandToProperty(null, "_albedoColor")
  31381. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  31382. __decorate([
  31383. BABYLON.serializeAsTexture(),
  31384. BABYLON.expandToProperty(null, "_albedoTexture")
  31385. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  31386. __decorate([
  31387. BABYLON.serializeAsColor3(),
  31388. BABYLON.expandToProperty(null, "_reflectivityColor")
  31389. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  31390. __decorate([
  31391. BABYLON.serialize(),
  31392. BABYLON.expandToProperty(null, "_microSurface")
  31393. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  31394. __decorate([
  31395. BABYLON.serializeAsTexture(),
  31396. BABYLON.expandToProperty(null, "_reflectivityTexture")
  31397. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  31398. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  31399. })(BABYLON || (BABYLON = {}));
  31400. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  31401. var BABYLON;
  31402. (function (BABYLON) {
  31403. BABYLON.CameraInputTypes = {};
  31404. var CameraInputsManager = (function () {
  31405. function CameraInputsManager(camera) {
  31406. this.attached = {};
  31407. this.camera = camera;
  31408. this.checkInputs = function () { };
  31409. }
  31410. CameraInputsManager.prototype.add = function (input) {
  31411. var type = input.getSimpleName();
  31412. if (this.attached[type]) {
  31413. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31414. return;
  31415. }
  31416. this.attached[type] = input;
  31417. input.camera = this.camera;
  31418. //for checkInputs, we are dynamically creating a function
  31419. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31420. if (input.checkInputs) {
  31421. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31422. }
  31423. if (this.attachedElement) {
  31424. input.attachControl(this.attachedElement);
  31425. }
  31426. };
  31427. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31428. for (var cam in this.attached) {
  31429. var input = this.attached[cam];
  31430. if (input === inputToRemove) {
  31431. input.detachControl(this.attachedElement);
  31432. delete this.attached[cam];
  31433. this.rebuildInputCheck();
  31434. }
  31435. }
  31436. };
  31437. CameraInputsManager.prototype.removeByType = function (inputType) {
  31438. for (var cam in this.attached) {
  31439. var input = this.attached[cam];
  31440. if (input.getTypeName() === inputType) {
  31441. input.detachControl(this.attachedElement);
  31442. delete this.attached[cam];
  31443. this.rebuildInputCheck();
  31444. }
  31445. }
  31446. };
  31447. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31448. var current = this.checkInputs;
  31449. return function () {
  31450. current();
  31451. fn();
  31452. };
  31453. };
  31454. CameraInputsManager.prototype.attachInput = function (input) {
  31455. input.attachControl(this.attachedElement, this.noPreventDefault);
  31456. };
  31457. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31458. if (this.attachedElement) {
  31459. return;
  31460. }
  31461. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31462. this.attachedElement = element;
  31463. this.noPreventDefault = noPreventDefault;
  31464. for (var cam in this.attached) {
  31465. var input = this.attached[cam];
  31466. this.attached[cam].attachControl(element, noPreventDefault);
  31467. }
  31468. };
  31469. CameraInputsManager.prototype.detachElement = function (element) {
  31470. if (this.attachedElement !== element) {
  31471. return;
  31472. }
  31473. for (var cam in this.attached) {
  31474. var input = this.attached[cam];
  31475. this.attached[cam].detachControl(element);
  31476. }
  31477. this.attachedElement = null;
  31478. };
  31479. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31480. this.checkInputs = function () { };
  31481. for (var cam in this.attached) {
  31482. var input = this.attached[cam];
  31483. if (input.checkInputs) {
  31484. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31485. }
  31486. }
  31487. };
  31488. CameraInputsManager.prototype.clear = function () {
  31489. if (this.attachedElement) {
  31490. this.detachElement(this.attachedElement);
  31491. }
  31492. this.attached = {};
  31493. this.attachedElement = null;
  31494. this.checkInputs = function () { };
  31495. };
  31496. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31497. var inputs = {};
  31498. for (var cam in this.attached) {
  31499. var input = this.attached[cam];
  31500. var res = BABYLON.SerializationHelper.Serialize(input);
  31501. inputs[input.getTypeName()] = res;
  31502. }
  31503. serializedCamera.inputsmgr = inputs;
  31504. };
  31505. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31506. var parsedInputs = parsedCamera.inputsmgr;
  31507. if (parsedInputs) {
  31508. this.clear();
  31509. for (var n in parsedInputs) {
  31510. var construct = BABYLON.CameraInputTypes[n];
  31511. if (construct) {
  31512. var parsedinput = parsedInputs[n];
  31513. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31514. this.add(input);
  31515. }
  31516. }
  31517. }
  31518. else {
  31519. //2016-03-08 this part is for managing backward compatibility
  31520. for (var n in this.attached) {
  31521. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31522. if (construct) {
  31523. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31524. this.remove(this.attached[n]);
  31525. this.add(input);
  31526. }
  31527. }
  31528. }
  31529. };
  31530. return CameraInputsManager;
  31531. }());
  31532. BABYLON.CameraInputsManager = CameraInputsManager;
  31533. })(BABYLON || (BABYLON = {}));
  31534. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31535. var BABYLON;
  31536. (function (BABYLON) {
  31537. var FreeCameraMouseInput = (function () {
  31538. function FreeCameraMouseInput(touchEnabled) {
  31539. if (touchEnabled === void 0) { touchEnabled = true; }
  31540. this.touchEnabled = touchEnabled;
  31541. this.buttons = [0, 1, 2];
  31542. this.angularSensibility = 2000.0;
  31543. }
  31544. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  31545. var _this = this;
  31546. var engine = this.camera.getEngine();
  31547. if (!this._pointerInput) {
  31548. this._pointerInput = function (p, s) {
  31549. var evt = p.event;
  31550. if (!_this.touchEnabled && evt.pointerType === "touch") {
  31551. return;
  31552. }
  31553. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31554. return;
  31555. }
  31556. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31557. try {
  31558. evt.srcElement.setPointerCapture(evt.pointerId);
  31559. }
  31560. catch (e) {
  31561. //Nothing to do with the error. Execution will continue.
  31562. }
  31563. _this.previousPosition = {
  31564. x: evt.clientX,
  31565. y: evt.clientY
  31566. };
  31567. if (!noPreventDefault) {
  31568. evt.preventDefault();
  31569. element.focus();
  31570. }
  31571. }
  31572. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31573. try {
  31574. evt.srcElement.releasePointerCapture(evt.pointerId);
  31575. }
  31576. catch (e) {
  31577. //Nothing to do with the error.
  31578. }
  31579. _this.previousPosition = null;
  31580. if (!noPreventDefault) {
  31581. evt.preventDefault();
  31582. }
  31583. }
  31584. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31585. if (!_this.previousPosition || engine.isPointerLock) {
  31586. return;
  31587. }
  31588. var offsetX = evt.clientX - _this.previousPosition.x;
  31589. var offsetY = evt.clientY - _this.previousPosition.y;
  31590. if (_this.camera.getScene().useRightHandedSystem) {
  31591. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31592. }
  31593. else {
  31594. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31595. }
  31596. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31597. _this.previousPosition = {
  31598. x: evt.clientX,
  31599. y: evt.clientY
  31600. };
  31601. if (!noPreventDefault) {
  31602. evt.preventDefault();
  31603. }
  31604. }
  31605. };
  31606. }
  31607. this._onMouseMove = function (evt) {
  31608. if (!engine.isPointerLock) {
  31609. return;
  31610. }
  31611. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31612. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31613. if (_this.camera.getScene().useRightHandedSystem) {
  31614. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  31615. }
  31616. else {
  31617. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  31618. }
  31619. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  31620. _this.previousPosition = null;
  31621. if (!noPreventDefault) {
  31622. evt.preventDefault();
  31623. }
  31624. };
  31625. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31626. element.addEventListener("mousemove", this._onMouseMove, false);
  31627. };
  31628. FreeCameraMouseInput.prototype.detachControl = function (element) {
  31629. if (this._observer && element) {
  31630. this.camera.getScene().onPointerObservable.remove(this._observer);
  31631. element.removeEventListener("mousemove", this._onMouseMove);
  31632. this._observer = null;
  31633. this._onMouseMove = null;
  31634. this.previousPosition = null;
  31635. }
  31636. };
  31637. FreeCameraMouseInput.prototype.getTypeName = function () {
  31638. return "FreeCameraMouseInput";
  31639. };
  31640. FreeCameraMouseInput.prototype.getSimpleName = function () {
  31641. return "mouse";
  31642. };
  31643. return FreeCameraMouseInput;
  31644. }());
  31645. __decorate([
  31646. BABYLON.serialize()
  31647. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  31648. __decorate([
  31649. BABYLON.serialize()
  31650. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  31651. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  31652. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  31653. })(BABYLON || (BABYLON = {}));
  31654. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  31655. var BABYLON;
  31656. (function (BABYLON) {
  31657. var FreeCameraKeyboardMoveInput = (function () {
  31658. function FreeCameraKeyboardMoveInput() {
  31659. this._keys = [];
  31660. this.keysUp = [38];
  31661. this.keysDown = [40];
  31662. this.keysLeft = [37];
  31663. this.keysRight = [39];
  31664. }
  31665. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31666. var _this = this;
  31667. if (!this._onKeyDown) {
  31668. element.tabIndex = 1;
  31669. this._onKeyDown = function (evt) {
  31670. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31671. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31672. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31673. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31674. var index = _this._keys.indexOf(evt.keyCode);
  31675. if (index === -1) {
  31676. _this._keys.push(evt.keyCode);
  31677. }
  31678. if (!noPreventDefault) {
  31679. evt.preventDefault();
  31680. }
  31681. }
  31682. };
  31683. this._onKeyUp = function (evt) {
  31684. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31685. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31686. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31687. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31688. var index = _this._keys.indexOf(evt.keyCode);
  31689. if (index >= 0) {
  31690. _this._keys.splice(index, 1);
  31691. }
  31692. if (!noPreventDefault) {
  31693. evt.preventDefault();
  31694. }
  31695. }
  31696. };
  31697. element.addEventListener("keydown", this._onKeyDown, false);
  31698. element.addEventListener("keyup", this._onKeyUp, false);
  31699. BABYLON.Tools.RegisterTopRootEvents([
  31700. { name: "blur", handler: this._onLostFocus }
  31701. ]);
  31702. }
  31703. };
  31704. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31705. if (this._onKeyDown) {
  31706. element.removeEventListener("keydown", this._onKeyDown);
  31707. element.removeEventListener("keyup", this._onKeyUp);
  31708. BABYLON.Tools.UnregisterTopRootEvents([
  31709. { name: "blur", handler: this._onLostFocus }
  31710. ]);
  31711. this._keys = [];
  31712. this._onKeyDown = null;
  31713. this._onKeyUp = null;
  31714. }
  31715. };
  31716. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31717. if (this._onKeyDown) {
  31718. var camera = this.camera;
  31719. // Keyboard
  31720. for (var index = 0; index < this._keys.length; index++) {
  31721. var keyCode = this._keys[index];
  31722. var speed = camera._computeLocalCameraSpeed();
  31723. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31724. camera._localDirection.copyFromFloats(-speed, 0, 0);
  31725. }
  31726. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31727. camera._localDirection.copyFromFloats(0, 0, speed);
  31728. }
  31729. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31730. camera._localDirection.copyFromFloats(speed, 0, 0);
  31731. }
  31732. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31733. camera._localDirection.copyFromFloats(0, 0, -speed);
  31734. }
  31735. if (camera.getScene().useRightHandedSystem) {
  31736. camera._localDirection.z *= -1;
  31737. }
  31738. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  31739. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  31740. camera.cameraDirection.addInPlace(camera._transformedDirection);
  31741. }
  31742. }
  31743. };
  31744. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31745. return "FreeCameraKeyboardMoveInput";
  31746. };
  31747. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  31748. this._keys = [];
  31749. };
  31750. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31751. return "keyboard";
  31752. };
  31753. return FreeCameraKeyboardMoveInput;
  31754. }());
  31755. __decorate([
  31756. BABYLON.serialize()
  31757. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31758. __decorate([
  31759. BABYLON.serialize()
  31760. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31761. __decorate([
  31762. BABYLON.serialize()
  31763. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31764. __decorate([
  31765. BABYLON.serialize()
  31766. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31767. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  31768. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  31769. })(BABYLON || (BABYLON = {}));
  31770. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  31771. var BABYLON;
  31772. (function (BABYLON) {
  31773. var FreeCameraInputsManager = (function (_super) {
  31774. __extends(FreeCameraInputsManager, _super);
  31775. function FreeCameraInputsManager(camera) {
  31776. return _super.call(this, camera) || this;
  31777. }
  31778. FreeCameraInputsManager.prototype.addKeyboard = function () {
  31779. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  31780. return this;
  31781. };
  31782. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  31783. if (touchEnabled === void 0) { touchEnabled = true; }
  31784. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  31785. return this;
  31786. };
  31787. FreeCameraInputsManager.prototype.addGamepad = function () {
  31788. this.add(new BABYLON.FreeCameraGamepadInput());
  31789. return this;
  31790. };
  31791. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  31792. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  31793. return this;
  31794. };
  31795. FreeCameraInputsManager.prototype.addTouch = function () {
  31796. this.add(new BABYLON.FreeCameraTouchInput());
  31797. return this;
  31798. };
  31799. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  31800. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  31801. return this;
  31802. };
  31803. return FreeCameraInputsManager;
  31804. }(BABYLON.CameraInputsManager));
  31805. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  31806. })(BABYLON || (BABYLON = {}));
  31807. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  31808. /// <reference path="babylon.camera.ts" />
  31809. var BABYLON;
  31810. (function (BABYLON) {
  31811. var TargetCamera = (function (_super) {
  31812. __extends(TargetCamera, _super);
  31813. function TargetCamera(name, position, scene) {
  31814. var _this = _super.call(this, name, position, scene) || this;
  31815. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31816. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31817. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31818. _this.speed = 2.0;
  31819. _this.noRotationConstraint = false;
  31820. _this.lockedTarget = null;
  31821. _this._currentTarget = BABYLON.Vector3.Zero();
  31822. _this._viewMatrix = BABYLON.Matrix.Zero();
  31823. _this._camMatrix = BABYLON.Matrix.Zero();
  31824. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31825. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31826. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31827. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31828. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31829. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31830. _this._tempMatrix = BABYLON.Matrix.Zero();
  31831. return _this;
  31832. }
  31833. TargetCamera.prototype.getFrontPosition = function (distance) {
  31834. var direction = this.getTarget().subtract(this.position);
  31835. direction.normalize();
  31836. direction.scaleInPlace(distance);
  31837. return this.globalPosition.add(direction);
  31838. };
  31839. TargetCamera.prototype._getLockedTargetPosition = function () {
  31840. if (!this.lockedTarget) {
  31841. return null;
  31842. }
  31843. if (this.lockedTarget.absolutePosition) {
  31844. this.lockedTarget.computeWorldMatrix();
  31845. }
  31846. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31847. };
  31848. // Cache
  31849. TargetCamera.prototype._initCache = function () {
  31850. _super.prototype._initCache.call(this);
  31851. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31852. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31853. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31854. };
  31855. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31856. if (!ignoreParentClass) {
  31857. _super.prototype._updateCache.call(this);
  31858. }
  31859. var lockedTargetPosition = this._getLockedTargetPosition();
  31860. if (!lockedTargetPosition) {
  31861. this._cache.lockedTarget = null;
  31862. }
  31863. else {
  31864. if (!this._cache.lockedTarget) {
  31865. this._cache.lockedTarget = lockedTargetPosition.clone();
  31866. }
  31867. else {
  31868. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31869. }
  31870. }
  31871. this._cache.rotation.copyFrom(this.rotation);
  31872. if (this.rotationQuaternion)
  31873. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31874. };
  31875. // Synchronized
  31876. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31877. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31878. return false;
  31879. }
  31880. var lockedTargetPosition = this._getLockedTargetPosition();
  31881. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31882. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31883. };
  31884. // Methods
  31885. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31886. var engine = this.getEngine();
  31887. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31888. };
  31889. // Target
  31890. TargetCamera.prototype.setTarget = function (target) {
  31891. this.upVector.normalize();
  31892. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31893. this._camMatrix.invert();
  31894. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31895. var vDir = target.subtract(this.position);
  31896. if (vDir.x >= 0.0) {
  31897. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31898. }
  31899. else {
  31900. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31901. }
  31902. this.rotation.z = 0;
  31903. if (isNaN(this.rotation.x)) {
  31904. this.rotation.x = 0;
  31905. }
  31906. if (isNaN(this.rotation.y)) {
  31907. this.rotation.y = 0;
  31908. }
  31909. if (isNaN(this.rotation.z)) {
  31910. this.rotation.z = 0;
  31911. }
  31912. if (this.rotationQuaternion) {
  31913. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31914. }
  31915. };
  31916. /**
  31917. * Return the current target position of the camera. This value is expressed in local space.
  31918. */
  31919. TargetCamera.prototype.getTarget = function () {
  31920. return this._currentTarget;
  31921. };
  31922. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31923. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31924. };
  31925. TargetCamera.prototype._updatePosition = function () {
  31926. if (this.parent) {
  31927. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31928. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31929. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31930. return;
  31931. }
  31932. this.position.addInPlace(this.cameraDirection);
  31933. };
  31934. TargetCamera.prototype._checkInputs = function () {
  31935. var needToMove = this._decideIfNeedsToMove();
  31936. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31937. // Move
  31938. if (needToMove) {
  31939. this._updatePosition();
  31940. }
  31941. // Rotate
  31942. if (needToRotate) {
  31943. this.rotation.x += this.cameraRotation.x;
  31944. this.rotation.y += this.cameraRotation.y;
  31945. //rotate, if quaternion is set and rotation was used
  31946. if (this.rotationQuaternion) {
  31947. var len = this.rotation.lengthSquared();
  31948. if (len) {
  31949. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31950. }
  31951. }
  31952. if (!this.noRotationConstraint) {
  31953. var limit = (Math.PI / 2) * 0.95;
  31954. if (this.rotation.x > limit)
  31955. this.rotation.x = limit;
  31956. if (this.rotation.x < -limit)
  31957. this.rotation.x = -limit;
  31958. }
  31959. }
  31960. // Inertia
  31961. if (needToMove) {
  31962. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31963. this.cameraDirection.x = 0;
  31964. }
  31965. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31966. this.cameraDirection.y = 0;
  31967. }
  31968. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31969. this.cameraDirection.z = 0;
  31970. }
  31971. this.cameraDirection.scaleInPlace(this.inertia);
  31972. }
  31973. if (needToRotate) {
  31974. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31975. this.cameraRotation.x = 0;
  31976. }
  31977. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31978. this.cameraRotation.y = 0;
  31979. }
  31980. this.cameraRotation.scaleInPlace(this.inertia);
  31981. }
  31982. _super.prototype._checkInputs.call(this);
  31983. };
  31984. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31985. if (this.rotationQuaternion) {
  31986. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31987. //update the up vector!
  31988. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31989. }
  31990. else {
  31991. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31992. }
  31993. };
  31994. TargetCamera.prototype._getViewMatrix = function () {
  31995. if (!this.lockedTarget) {
  31996. // Compute
  31997. this._updateCameraRotationMatrix();
  31998. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31999. // Computing target and final matrix
  32000. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  32001. }
  32002. else {
  32003. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  32004. }
  32005. if (this.getScene().useRightHandedSystem) {
  32006. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32007. }
  32008. else {
  32009. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  32010. }
  32011. return this._viewMatrix;
  32012. };
  32013. /**
  32014. * @override
  32015. * Override Camera.createRigCamera
  32016. */
  32017. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32018. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  32019. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  32020. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  32021. if (!this.rotationQuaternion) {
  32022. this.rotationQuaternion = new BABYLON.Quaternion();
  32023. }
  32024. rigCamera._cameraRigParams = {};
  32025. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  32026. }
  32027. return rigCamera;
  32028. }
  32029. return null;
  32030. };
  32031. /**
  32032. * @override
  32033. * Override Camera._updateRigCameras
  32034. */
  32035. TargetCamera.prototype._updateRigCameras = function () {
  32036. var camLeft = this._rigCameras[0];
  32037. var camRight = this._rigCameras[1];
  32038. switch (this.cameraRigMode) {
  32039. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32040. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32041. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32042. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32043. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  32044. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  32045. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  32046. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  32047. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  32048. camLeft.setTarget(this.getTarget());
  32049. camRight.setTarget(this.getTarget());
  32050. break;
  32051. case BABYLON.Camera.RIG_MODE_VR:
  32052. if (camLeft.rotationQuaternion) {
  32053. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32054. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  32055. }
  32056. else {
  32057. camLeft.rotation.copyFrom(this.rotation);
  32058. camRight.rotation.copyFrom(this.rotation);
  32059. }
  32060. camLeft.position.copyFrom(this.position);
  32061. camRight.position.copyFrom(this.position);
  32062. break;
  32063. }
  32064. _super.prototype._updateRigCameras.call(this);
  32065. };
  32066. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  32067. if (!this._rigCamTransformMatrix) {
  32068. this._rigCamTransformMatrix = new BABYLON.Matrix();
  32069. }
  32070. var target = this.getTarget();
  32071. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  32072. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  32073. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  32074. };
  32075. TargetCamera.prototype.getClassName = function () {
  32076. return "TargetCamera";
  32077. };
  32078. return TargetCamera;
  32079. }(BABYLON.Camera));
  32080. __decorate([
  32081. BABYLON.serializeAsVector3()
  32082. ], TargetCamera.prototype, "rotation", void 0);
  32083. __decorate([
  32084. BABYLON.serialize()
  32085. ], TargetCamera.prototype, "speed", void 0);
  32086. __decorate([
  32087. BABYLON.serializeAsMeshReference("lockedTargetId")
  32088. ], TargetCamera.prototype, "lockedTarget", void 0);
  32089. BABYLON.TargetCamera = TargetCamera;
  32090. })(BABYLON || (BABYLON = {}));
  32091. //# sourceMappingURL=babylon.targetCamera.js.map
  32092. var BABYLON;
  32093. (function (BABYLON) {
  32094. var FreeCamera = (function (_super) {
  32095. __extends(FreeCamera, _super);
  32096. function FreeCamera(name, position, scene) {
  32097. var _this = _super.call(this, name, position, scene) || this;
  32098. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  32099. _this.checkCollisions = false;
  32100. _this.applyGravity = false;
  32101. _this._needMoveForGravity = false;
  32102. _this._oldPosition = BABYLON.Vector3.Zero();
  32103. _this._diffPosition = BABYLON.Vector3.Zero();
  32104. _this._newPosition = BABYLON.Vector3.Zero();
  32105. // Collisions
  32106. _this._collisionMask = -1;
  32107. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32108. if (collidedMesh === void 0) { collidedMesh = null; }
  32109. //TODO move this to the collision coordinator!
  32110. if (_this.getScene().workerCollisions)
  32111. newPosition.multiplyInPlace(_this._collider.radius);
  32112. var updatePosition = function (newPos) {
  32113. _this._newPosition.copyFrom(newPos);
  32114. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  32115. var oldPosition = _this.position.clone();
  32116. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  32117. _this.position.addInPlace(_this._diffPosition);
  32118. if (_this.onCollide && collidedMesh) {
  32119. _this.onCollide(collidedMesh);
  32120. }
  32121. }
  32122. };
  32123. updatePosition(newPosition);
  32124. };
  32125. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  32126. _this.inputs.addKeyboard().addMouse();
  32127. return _this;
  32128. }
  32129. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  32130. //-- begin properties for backward compatibility for inputs
  32131. get: function () {
  32132. var mouse = this.inputs.attached["mouse"];
  32133. if (mouse)
  32134. return mouse.angularSensibility;
  32135. },
  32136. set: function (value) {
  32137. var mouse = this.inputs.attached["mouse"];
  32138. if (mouse)
  32139. mouse.angularSensibility = value;
  32140. },
  32141. enumerable: true,
  32142. configurable: true
  32143. });
  32144. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  32145. get: function () {
  32146. var keyboard = this.inputs.attached["keyboard"];
  32147. if (keyboard)
  32148. return keyboard.keysUp;
  32149. },
  32150. set: function (value) {
  32151. var keyboard = this.inputs.attached["keyboard"];
  32152. if (keyboard)
  32153. keyboard.keysUp = value;
  32154. },
  32155. enumerable: true,
  32156. configurable: true
  32157. });
  32158. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  32159. get: function () {
  32160. var keyboard = this.inputs.attached["keyboard"];
  32161. if (keyboard)
  32162. return keyboard.keysDown;
  32163. },
  32164. set: function (value) {
  32165. var keyboard = this.inputs.attached["keyboard"];
  32166. if (keyboard)
  32167. keyboard.keysDown = value;
  32168. },
  32169. enumerable: true,
  32170. configurable: true
  32171. });
  32172. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  32173. get: function () {
  32174. var keyboard = this.inputs.attached["keyboard"];
  32175. if (keyboard)
  32176. return keyboard.keysLeft;
  32177. },
  32178. set: function (value) {
  32179. var keyboard = this.inputs.attached["keyboard"];
  32180. if (keyboard)
  32181. keyboard.keysLeft = value;
  32182. },
  32183. enumerable: true,
  32184. configurable: true
  32185. });
  32186. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  32187. get: function () {
  32188. var keyboard = this.inputs.attached["keyboard"];
  32189. if (keyboard)
  32190. return keyboard.keysRight;
  32191. },
  32192. set: function (value) {
  32193. var keyboard = this.inputs.attached["keyboard"];
  32194. if (keyboard)
  32195. keyboard.keysRight = value;
  32196. },
  32197. enumerable: true,
  32198. configurable: true
  32199. });
  32200. // Controls
  32201. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  32202. this.inputs.attachElement(element, noPreventDefault);
  32203. };
  32204. FreeCamera.prototype.detachControl = function (element) {
  32205. this.inputs.detachElement(element);
  32206. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  32207. this.cameraRotation = new BABYLON.Vector2(0, 0);
  32208. };
  32209. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  32210. get: function () {
  32211. return this._collisionMask;
  32212. },
  32213. set: function (mask) {
  32214. this._collisionMask = !isNaN(mask) ? mask : -1;
  32215. },
  32216. enumerable: true,
  32217. configurable: true
  32218. });
  32219. FreeCamera.prototype._collideWithWorld = function (velocity) {
  32220. var globalPosition;
  32221. if (this.parent) {
  32222. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  32223. }
  32224. else {
  32225. globalPosition = this.position;
  32226. }
  32227. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  32228. if (!this._collider) {
  32229. this._collider = new BABYLON.Collider();
  32230. }
  32231. this._collider.radius = this.ellipsoid;
  32232. this._collider.collisionMask = this._collisionMask;
  32233. //no need for clone, as long as gravity is not on.
  32234. var actualVelocity = velocity;
  32235. //add gravity to the velocity to prevent the dual-collision checking
  32236. if (this.applyGravity) {
  32237. //this prevents mending with cameraDirection, a global variable of the free camera class.
  32238. actualVelocity = velocity.add(this.getScene().gravity);
  32239. }
  32240. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32241. };
  32242. FreeCamera.prototype._checkInputs = function () {
  32243. if (!this._localDirection) {
  32244. this._localDirection = BABYLON.Vector3.Zero();
  32245. this._transformedDirection = BABYLON.Vector3.Zero();
  32246. }
  32247. this.inputs.checkInputs();
  32248. _super.prototype._checkInputs.call(this);
  32249. };
  32250. FreeCamera.prototype._decideIfNeedsToMove = function () {
  32251. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  32252. };
  32253. FreeCamera.prototype._updatePosition = function () {
  32254. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  32255. this._collideWithWorld(this.cameraDirection);
  32256. }
  32257. else {
  32258. _super.prototype._updatePosition.call(this);
  32259. }
  32260. };
  32261. FreeCamera.prototype.dispose = function () {
  32262. this.inputs.clear();
  32263. _super.prototype.dispose.call(this);
  32264. };
  32265. FreeCamera.prototype.getClassName = function () {
  32266. return "FreeCamera";
  32267. };
  32268. return FreeCamera;
  32269. }(BABYLON.TargetCamera));
  32270. __decorate([
  32271. BABYLON.serializeAsVector3()
  32272. ], FreeCamera.prototype, "ellipsoid", void 0);
  32273. __decorate([
  32274. BABYLON.serialize()
  32275. ], FreeCamera.prototype, "checkCollisions", void 0);
  32276. __decorate([
  32277. BABYLON.serialize()
  32278. ], FreeCamera.prototype, "applyGravity", void 0);
  32279. BABYLON.FreeCamera = FreeCamera;
  32280. })(BABYLON || (BABYLON = {}));
  32281. //# sourceMappingURL=babylon.freeCamera.js.map
  32282. var BABYLON;
  32283. (function (BABYLON) {
  32284. var ArcRotateCameraKeyboardMoveInput = (function () {
  32285. function ArcRotateCameraKeyboardMoveInput() {
  32286. this._keys = [];
  32287. this.keysUp = [38];
  32288. this.keysDown = [40];
  32289. this.keysLeft = [37];
  32290. this.keysRight = [39];
  32291. }
  32292. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  32293. var _this = this;
  32294. element.tabIndex = 1;
  32295. this._onKeyDown = function (evt) {
  32296. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32297. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32298. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32299. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32300. var index = _this._keys.indexOf(evt.keyCode);
  32301. if (index === -1) {
  32302. _this._keys.push(evt.keyCode);
  32303. }
  32304. if (evt.preventDefault) {
  32305. if (!noPreventDefault) {
  32306. evt.preventDefault();
  32307. }
  32308. }
  32309. }
  32310. };
  32311. this._onKeyUp = function (evt) {
  32312. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  32313. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  32314. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  32315. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  32316. var index = _this._keys.indexOf(evt.keyCode);
  32317. if (index >= 0) {
  32318. _this._keys.splice(index, 1);
  32319. }
  32320. if (evt.preventDefault) {
  32321. if (!noPreventDefault) {
  32322. evt.preventDefault();
  32323. }
  32324. }
  32325. }
  32326. };
  32327. this._onLostFocus = function () {
  32328. _this._keys = [];
  32329. };
  32330. element.addEventListener("keydown", this._onKeyDown, false);
  32331. element.addEventListener("keyup", this._onKeyUp, false);
  32332. BABYLON.Tools.RegisterTopRootEvents([
  32333. { name: "blur", handler: this._onLostFocus }
  32334. ]);
  32335. };
  32336. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  32337. if (element) {
  32338. element.removeEventListener("keydown", this._onKeyDown);
  32339. element.removeEventListener("keyup", this._onKeyUp);
  32340. }
  32341. BABYLON.Tools.UnregisterTopRootEvents([
  32342. { name: "blur", handler: this._onLostFocus }
  32343. ]);
  32344. this._keys = [];
  32345. this._onKeyDown = null;
  32346. this._onKeyUp = null;
  32347. this._onLostFocus = null;
  32348. };
  32349. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  32350. if (this._onKeyDown) {
  32351. var camera = this.camera;
  32352. for (var index = 0; index < this._keys.length; index++) {
  32353. var keyCode = this._keys[index];
  32354. if (this.keysLeft.indexOf(keyCode) !== -1) {
  32355. camera.inertialAlphaOffset -= 0.01;
  32356. }
  32357. else if (this.keysUp.indexOf(keyCode) !== -1) {
  32358. camera.inertialBetaOffset -= 0.01;
  32359. }
  32360. else if (this.keysRight.indexOf(keyCode) !== -1) {
  32361. camera.inertialAlphaOffset += 0.01;
  32362. }
  32363. else if (this.keysDown.indexOf(keyCode) !== -1) {
  32364. camera.inertialBetaOffset += 0.01;
  32365. }
  32366. }
  32367. }
  32368. };
  32369. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  32370. return "ArcRotateCameraKeyboardMoveInput";
  32371. };
  32372. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  32373. return "keyboard";
  32374. };
  32375. return ArcRotateCameraKeyboardMoveInput;
  32376. }());
  32377. __decorate([
  32378. BABYLON.serialize()
  32379. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  32380. __decorate([
  32381. BABYLON.serialize()
  32382. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  32383. __decorate([
  32384. BABYLON.serialize()
  32385. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  32386. __decorate([
  32387. BABYLON.serialize()
  32388. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  32389. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  32390. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  32391. })(BABYLON || (BABYLON = {}));
  32392. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  32393. var BABYLON;
  32394. (function (BABYLON) {
  32395. var ArcRotateCameraMouseWheelInput = (function () {
  32396. function ArcRotateCameraMouseWheelInput() {
  32397. this.wheelPrecision = 3.0;
  32398. }
  32399. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  32400. var _this = this;
  32401. this._wheel = function (p, s) {
  32402. //sanity check - this should be a PointerWheel event.
  32403. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  32404. return;
  32405. var event = p.event;
  32406. var delta = 0;
  32407. if (event.wheelDelta) {
  32408. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  32409. }
  32410. else if (event.detail) {
  32411. delta = -event.detail / _this.wheelPrecision;
  32412. }
  32413. if (delta)
  32414. _this.camera.inertialRadiusOffset += delta;
  32415. if (event.preventDefault) {
  32416. if (!noPreventDefault) {
  32417. event.preventDefault();
  32418. }
  32419. }
  32420. };
  32421. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  32422. };
  32423. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  32424. if (this._observer && element) {
  32425. this.camera.getScene().onPointerObservable.remove(this._observer);
  32426. this._observer = null;
  32427. this._wheel = null;
  32428. }
  32429. };
  32430. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  32431. return "ArcRotateCameraMouseWheelInput";
  32432. };
  32433. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  32434. return "mousewheel";
  32435. };
  32436. return ArcRotateCameraMouseWheelInput;
  32437. }());
  32438. __decorate([
  32439. BABYLON.serialize()
  32440. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  32441. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  32442. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  32443. })(BABYLON || (BABYLON = {}));
  32444. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  32445. var BABYLON;
  32446. (function (BABYLON) {
  32447. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  32448. var ArcRotateCameraPointersInput = (function () {
  32449. function ArcRotateCameraPointersInput() {
  32450. this.buttons = [0, 1, 2];
  32451. this.angularSensibilityX = 1000.0;
  32452. this.angularSensibilityY = 1000.0;
  32453. this.pinchPrecision = 6.0;
  32454. this.panningSensibility = 50.0;
  32455. this._isPanClick = false;
  32456. this.pinchInwards = true;
  32457. }
  32458. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  32459. var _this = this;
  32460. var engine = this.camera.getEngine();
  32461. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  32462. var pointA, pointB;
  32463. var previousPinchDistance = 0;
  32464. this._pointerInput = function (p, s) {
  32465. var evt = p.event;
  32466. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  32467. return;
  32468. }
  32469. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  32470. try {
  32471. evt.srcElement.setPointerCapture(evt.pointerId);
  32472. }
  32473. catch (e) {
  32474. //Nothing to do with the error. Execution will continue.
  32475. }
  32476. // Manage panning with pan button click
  32477. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  32478. // manage pointers
  32479. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  32480. if (pointA === undefined) {
  32481. pointA = cacheSoloPointer;
  32482. }
  32483. else if (pointB === undefined) {
  32484. pointB = cacheSoloPointer;
  32485. }
  32486. if (!noPreventDefault) {
  32487. evt.preventDefault();
  32488. element.focus();
  32489. }
  32490. }
  32491. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  32492. try {
  32493. evt.srcElement.releasePointerCapture(evt.pointerId);
  32494. }
  32495. catch (e) {
  32496. //Nothing to do with the error.
  32497. }
  32498. cacheSoloPointer = null;
  32499. previousPinchDistance = 0;
  32500. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  32501. //but emptying completly pointers collection is required to fix a bug on iPhone :
  32502. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  32503. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  32504. pointA = pointB = undefined;
  32505. if (!noPreventDefault) {
  32506. evt.preventDefault();
  32507. }
  32508. }
  32509. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  32510. if (!noPreventDefault) {
  32511. evt.preventDefault();
  32512. }
  32513. // One button down
  32514. if (pointA && pointB === undefined) {
  32515. if (_this.panningSensibility !== 0 &&
  32516. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  32517. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  32518. _this.camera
  32519. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  32520. _this.camera
  32521. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  32522. }
  32523. else {
  32524. var offsetX = evt.clientX - cacheSoloPointer.x;
  32525. var offsetY = evt.clientY - cacheSoloPointer.y;
  32526. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32527. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32528. }
  32529. cacheSoloPointer.x = evt.clientX;
  32530. cacheSoloPointer.y = evt.clientY;
  32531. }
  32532. else if (pointA && pointB) {
  32533. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  32534. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  32535. ed.x = evt.clientX;
  32536. ed.y = evt.clientY;
  32537. var direction = _this.pinchInwards ? 1 : -1;
  32538. var distX = pointA.x - pointB.x;
  32539. var distY = pointA.y - pointB.y;
  32540. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  32541. if (previousPinchDistance === 0) {
  32542. previousPinchDistance = pinchSquaredDistance;
  32543. return;
  32544. }
  32545. if (pinchSquaredDistance !== previousPinchDistance) {
  32546. _this.camera
  32547. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  32548. (_this.pinchPrecision *
  32549. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  32550. direction);
  32551. previousPinchDistance = pinchSquaredDistance;
  32552. }
  32553. }
  32554. }
  32555. };
  32556. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  32557. this._onContextMenu = function (evt) {
  32558. evt.preventDefault();
  32559. };
  32560. if (!this.camera._useCtrlForPanning) {
  32561. element.addEventListener("contextmenu", this._onContextMenu, false);
  32562. }
  32563. this._onLostFocus = function () {
  32564. //this._keys = [];
  32565. pointA = pointB = undefined;
  32566. previousPinchDistance = 0;
  32567. cacheSoloPointer = null;
  32568. };
  32569. this._onMouseMove = function (evt) {
  32570. if (!engine.isPointerLock) {
  32571. return;
  32572. }
  32573. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  32574. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  32575. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  32576. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  32577. if (!noPreventDefault) {
  32578. evt.preventDefault();
  32579. }
  32580. };
  32581. this._onGestureStart = function (e) {
  32582. if (window.MSGesture === undefined) {
  32583. return;
  32584. }
  32585. if (!_this._MSGestureHandler) {
  32586. _this._MSGestureHandler = new MSGesture();
  32587. _this._MSGestureHandler.target = element;
  32588. }
  32589. _this._MSGestureHandler.addPointer(e.pointerId);
  32590. };
  32591. this._onGesture = function (e) {
  32592. _this.camera.radius *= e.scale;
  32593. if (e.preventDefault) {
  32594. if (!noPreventDefault) {
  32595. e.stopPropagation();
  32596. e.preventDefault();
  32597. }
  32598. }
  32599. };
  32600. element.addEventListener("mousemove", this._onMouseMove, false);
  32601. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  32602. element.addEventListener("MSGestureChange", this._onGesture, false);
  32603. BABYLON.Tools.RegisterTopRootEvents([
  32604. { name: "blur", handler: this._onLostFocus }
  32605. ]);
  32606. };
  32607. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  32608. if (element && this._observer) {
  32609. this.camera.getScene().onPointerObservable.remove(this._observer);
  32610. this._observer = null;
  32611. element.removeEventListener("contextmenu", this._onContextMenu);
  32612. element.removeEventListener("mousemove", this._onMouseMove);
  32613. element.removeEventListener("MSPointerDown", this._onGestureStart);
  32614. element.removeEventListener("MSGestureChange", this._onGesture);
  32615. this._isPanClick = false;
  32616. this.pinchInwards = true;
  32617. this._onMouseMove = null;
  32618. this._onGestureStart = null;
  32619. this._onGesture = null;
  32620. this._MSGestureHandler = null;
  32621. this._onLostFocus = null;
  32622. this._onContextMenu = null;
  32623. }
  32624. BABYLON.Tools.UnregisterTopRootEvents([
  32625. { name: "blur", handler: this._onLostFocus }
  32626. ]);
  32627. };
  32628. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  32629. return "ArcRotateCameraPointersInput";
  32630. };
  32631. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  32632. return "pointers";
  32633. };
  32634. return ArcRotateCameraPointersInput;
  32635. }());
  32636. __decorate([
  32637. BABYLON.serialize()
  32638. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  32639. __decorate([
  32640. BABYLON.serialize()
  32641. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  32642. __decorate([
  32643. BABYLON.serialize()
  32644. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  32645. __decorate([
  32646. BABYLON.serialize()
  32647. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  32648. __decorate([
  32649. BABYLON.serialize()
  32650. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  32651. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  32652. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  32653. })(BABYLON || (BABYLON = {}));
  32654. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  32655. /// <reference path="babylon.targetCamera.ts" />
  32656. /// <reference path="..\Tools\babylon.tools.ts" />
  32657. var BABYLON;
  32658. (function (BABYLON) {
  32659. var ArcRotateCamera = (function (_super) {
  32660. __extends(ArcRotateCamera, _super);
  32661. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  32662. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  32663. _this.inertialAlphaOffset = 0;
  32664. _this.inertialBetaOffset = 0;
  32665. _this.inertialRadiusOffset = 0;
  32666. _this.lowerAlphaLimit = null;
  32667. _this.upperAlphaLimit = null;
  32668. _this.lowerBetaLimit = 0.01;
  32669. _this.upperBetaLimit = Math.PI;
  32670. _this.lowerRadiusLimit = null;
  32671. _this.upperRadiusLimit = null;
  32672. _this.inertialPanningX = 0;
  32673. _this.inertialPanningY = 0;
  32674. _this.panningInertia = 0.9;
  32675. //-- end properties for backward compatibility for inputs
  32676. _this.zoomOnFactor = 1;
  32677. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  32678. _this.allowUpsideDown = true;
  32679. _this._viewMatrix = new BABYLON.Matrix();
  32680. // Panning
  32681. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  32682. _this.checkCollisions = false;
  32683. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32684. _this._previousPosition = BABYLON.Vector3.Zero();
  32685. _this._collisionVelocity = BABYLON.Vector3.Zero();
  32686. _this._newPosition = BABYLON.Vector3.Zero();
  32687. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  32688. if (collidedMesh === void 0) { collidedMesh = null; }
  32689. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  32690. newPosition.multiplyInPlace(_this._collider.radius);
  32691. }
  32692. if (!collidedMesh) {
  32693. _this._previousPosition.copyFrom(_this.position);
  32694. }
  32695. else {
  32696. _this.setPosition(newPosition);
  32697. if (_this.onCollide) {
  32698. _this.onCollide(collidedMesh);
  32699. }
  32700. }
  32701. // Recompute because of constraints
  32702. var cosa = Math.cos(_this.alpha);
  32703. var sina = Math.sin(_this.alpha);
  32704. var cosb = Math.cos(_this.beta);
  32705. var sinb = Math.sin(_this.beta);
  32706. if (sinb === 0) {
  32707. sinb = 0.0001;
  32708. }
  32709. var target = _this._getTargetPosition();
  32710. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  32711. _this.position.copyFrom(_this._newPosition);
  32712. var up = _this.upVector;
  32713. if (_this.allowUpsideDown && _this.beta < 0) {
  32714. up = up.clone();
  32715. up = up.negate();
  32716. }
  32717. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  32718. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  32719. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  32720. _this._collisionTriggered = false;
  32721. };
  32722. _this._target = BABYLON.Vector3.Zero();
  32723. if (target) {
  32724. _this.setTarget(target);
  32725. }
  32726. _this.alpha = alpha;
  32727. _this.beta = beta;
  32728. _this.radius = radius;
  32729. _this.getViewMatrix();
  32730. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  32731. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  32732. return _this;
  32733. }
  32734. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  32735. get: function () {
  32736. return this._target;
  32737. },
  32738. set: function (value) {
  32739. this.setTarget(value);
  32740. },
  32741. enumerable: true,
  32742. configurable: true
  32743. });
  32744. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  32745. //-- begin properties for backward compatibility for inputs
  32746. get: function () {
  32747. var pointers = this.inputs.attached["pointers"];
  32748. if (pointers)
  32749. return pointers.angularSensibilityX;
  32750. },
  32751. set: function (value) {
  32752. var pointers = this.inputs.attached["pointers"];
  32753. if (pointers) {
  32754. pointers.angularSensibilityX = value;
  32755. }
  32756. },
  32757. enumerable: true,
  32758. configurable: true
  32759. });
  32760. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  32761. get: function () {
  32762. var pointers = this.inputs.attached["pointers"];
  32763. if (pointers)
  32764. return pointers.angularSensibilityY;
  32765. },
  32766. set: function (value) {
  32767. var pointers = this.inputs.attached["pointers"];
  32768. if (pointers) {
  32769. pointers.angularSensibilityY = value;
  32770. }
  32771. },
  32772. enumerable: true,
  32773. configurable: true
  32774. });
  32775. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  32776. get: function () {
  32777. var pointers = this.inputs.attached["pointers"];
  32778. if (pointers)
  32779. return pointers.pinchPrecision;
  32780. },
  32781. set: function (value) {
  32782. var pointers = this.inputs.attached["pointers"];
  32783. if (pointers) {
  32784. pointers.pinchPrecision = value;
  32785. }
  32786. },
  32787. enumerable: true,
  32788. configurable: true
  32789. });
  32790. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  32791. get: function () {
  32792. var pointers = this.inputs.attached["pointers"];
  32793. if (pointers)
  32794. return pointers.panningSensibility;
  32795. },
  32796. set: function (value) {
  32797. var pointers = this.inputs.attached["pointers"];
  32798. if (pointers) {
  32799. pointers.panningSensibility = value;
  32800. }
  32801. },
  32802. enumerable: true,
  32803. configurable: true
  32804. });
  32805. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  32806. get: function () {
  32807. var keyboard = this.inputs.attached["keyboard"];
  32808. if (keyboard)
  32809. return keyboard.keysUp;
  32810. },
  32811. set: function (value) {
  32812. var keyboard = this.inputs.attached["keyboard"];
  32813. if (keyboard)
  32814. keyboard.keysUp = value;
  32815. },
  32816. enumerable: true,
  32817. configurable: true
  32818. });
  32819. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  32820. get: function () {
  32821. var keyboard = this.inputs.attached["keyboard"];
  32822. if (keyboard)
  32823. return keyboard.keysDown;
  32824. },
  32825. set: function (value) {
  32826. var keyboard = this.inputs.attached["keyboard"];
  32827. if (keyboard)
  32828. keyboard.keysDown = value;
  32829. },
  32830. enumerable: true,
  32831. configurable: true
  32832. });
  32833. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  32834. get: function () {
  32835. var keyboard = this.inputs.attached["keyboard"];
  32836. if (keyboard)
  32837. return keyboard.keysLeft;
  32838. },
  32839. set: function (value) {
  32840. var keyboard = this.inputs.attached["keyboard"];
  32841. if (keyboard)
  32842. keyboard.keysLeft = value;
  32843. },
  32844. enumerable: true,
  32845. configurable: true
  32846. });
  32847. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  32848. get: function () {
  32849. var keyboard = this.inputs.attached["keyboard"];
  32850. if (keyboard)
  32851. return keyboard.keysRight;
  32852. },
  32853. set: function (value) {
  32854. var keyboard = this.inputs.attached["keyboard"];
  32855. if (keyboard)
  32856. keyboard.keysRight = value;
  32857. },
  32858. enumerable: true,
  32859. configurable: true
  32860. });
  32861. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  32862. get: function () {
  32863. var mousewheel = this.inputs.attached["mousewheel"];
  32864. if (mousewheel)
  32865. return mousewheel.wheelPrecision;
  32866. },
  32867. set: function (value) {
  32868. var mousewheel = this.inputs.attached["mousewheel"];
  32869. if (mousewheel)
  32870. mousewheel.wheelPrecision = value;
  32871. },
  32872. enumerable: true,
  32873. configurable: true
  32874. });
  32875. // Cache
  32876. ArcRotateCamera.prototype._initCache = function () {
  32877. _super.prototype._initCache.call(this);
  32878. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32879. this._cache.alpha = undefined;
  32880. this._cache.beta = undefined;
  32881. this._cache.radius = undefined;
  32882. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32883. };
  32884. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32885. if (!ignoreParentClass) {
  32886. _super.prototype._updateCache.call(this);
  32887. }
  32888. this._cache._target.copyFrom(this._getTargetPosition());
  32889. this._cache.alpha = this.alpha;
  32890. this._cache.beta = this.beta;
  32891. this._cache.radius = this.radius;
  32892. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32893. };
  32894. ArcRotateCamera.prototype._getTargetPosition = function () {
  32895. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32896. var pos = this._targetHost.getAbsolutePosition();
  32897. if (this._targetBoundingCenter) {
  32898. pos.addToRef(this._targetBoundingCenter, this._target);
  32899. }
  32900. else {
  32901. this._target.copyFrom(pos);
  32902. }
  32903. }
  32904. return this._target;
  32905. };
  32906. // Synchronized
  32907. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32908. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32909. return false;
  32910. return this._cache._target.equals(this._getTargetPosition())
  32911. && this._cache.alpha === this.alpha
  32912. && this._cache.beta === this.beta
  32913. && this._cache.radius === this.radius
  32914. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32915. };
  32916. // Methods
  32917. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32918. var _this = this;
  32919. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32920. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32921. this._useCtrlForPanning = useCtrlForPanning;
  32922. this._panningMouseButton = panningMouseButton;
  32923. this.inputs.attachElement(element, noPreventDefault);
  32924. this._reset = function () {
  32925. _this.inertialAlphaOffset = 0;
  32926. _this.inertialBetaOffset = 0;
  32927. _this.inertialRadiusOffset = 0;
  32928. };
  32929. };
  32930. ArcRotateCamera.prototype.detachControl = function (element) {
  32931. this.inputs.detachElement(element);
  32932. if (this._reset) {
  32933. this._reset();
  32934. }
  32935. };
  32936. ArcRotateCamera.prototype._checkInputs = function () {
  32937. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32938. if (this._collisionTriggered) {
  32939. return;
  32940. }
  32941. this.inputs.checkInputs();
  32942. // Inertia
  32943. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32944. if (this.getScene().useRightHandedSystem) {
  32945. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32946. }
  32947. else {
  32948. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32949. }
  32950. this.beta += this.inertialBetaOffset;
  32951. this.radius -= this.inertialRadiusOffset;
  32952. this.inertialAlphaOffset *= this.inertia;
  32953. this.inertialBetaOffset *= this.inertia;
  32954. this.inertialRadiusOffset *= this.inertia;
  32955. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32956. this.inertialAlphaOffset = 0;
  32957. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32958. this.inertialBetaOffset = 0;
  32959. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32960. this.inertialRadiusOffset = 0;
  32961. }
  32962. // Panning inertia
  32963. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32964. if (!this._localDirection) {
  32965. this._localDirection = BABYLON.Vector3.Zero();
  32966. this._transformedDirection = BABYLON.Vector3.Zero();
  32967. }
  32968. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32969. this._localDirection.multiplyInPlace(this.panningAxis);
  32970. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32971. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32972. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32973. if (!this.panningAxis.y) {
  32974. this._transformedDirection.y = 0;
  32975. }
  32976. if (!this._targetHost) {
  32977. this._target.addInPlace(this._transformedDirection);
  32978. }
  32979. this.inertialPanningX *= this.panningInertia;
  32980. this.inertialPanningY *= this.panningInertia;
  32981. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32982. this.inertialPanningX = 0;
  32983. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32984. this.inertialPanningY = 0;
  32985. }
  32986. // Limits
  32987. this._checkLimits();
  32988. _super.prototype._checkInputs.call(this);
  32989. };
  32990. ArcRotateCamera.prototype._checkLimits = function () {
  32991. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32992. if (this.allowUpsideDown && this.beta > Math.PI) {
  32993. this.beta = this.beta - (2 * Math.PI);
  32994. }
  32995. }
  32996. else {
  32997. if (this.beta < this.lowerBetaLimit) {
  32998. this.beta = this.lowerBetaLimit;
  32999. }
  33000. }
  33001. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  33002. if (this.allowUpsideDown && this.beta < -Math.PI) {
  33003. this.beta = this.beta + (2 * Math.PI);
  33004. }
  33005. }
  33006. else {
  33007. if (this.beta > this.upperBetaLimit) {
  33008. this.beta = this.upperBetaLimit;
  33009. }
  33010. }
  33011. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  33012. this.alpha = this.lowerAlphaLimit;
  33013. }
  33014. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  33015. this.alpha = this.upperAlphaLimit;
  33016. }
  33017. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  33018. this.radius = this.lowerRadiusLimit;
  33019. }
  33020. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  33021. this.radius = this.upperRadiusLimit;
  33022. }
  33023. };
  33024. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  33025. var radiusv3 = this.position.subtract(this._getTargetPosition());
  33026. this.radius = radiusv3.length();
  33027. // Alpha
  33028. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  33029. if (radiusv3.z < 0) {
  33030. this.alpha = 2 * Math.PI - this.alpha;
  33031. }
  33032. // Beta
  33033. this.beta = Math.acos(radiusv3.y / this.radius);
  33034. this._checkLimits();
  33035. };
  33036. ArcRotateCamera.prototype.setPosition = function (position) {
  33037. if (this.position.equals(position)) {
  33038. return;
  33039. }
  33040. this.position.copyFrom(position);
  33041. this.rebuildAnglesAndRadius();
  33042. };
  33043. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  33044. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  33045. if (allowSamePosition === void 0) { allowSamePosition = false; }
  33046. if (target.getBoundingInfo) {
  33047. if (toBoundingCenter) {
  33048. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  33049. }
  33050. else {
  33051. this._targetBoundingCenter = null;
  33052. }
  33053. this._targetHost = target;
  33054. this._target = this._getTargetPosition();
  33055. }
  33056. else {
  33057. var newTarget = target;
  33058. var currentTarget = this._getTargetPosition();
  33059. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  33060. return;
  33061. }
  33062. this._target = newTarget;
  33063. this._targetBoundingCenter = null;
  33064. }
  33065. this.rebuildAnglesAndRadius();
  33066. };
  33067. ArcRotateCamera.prototype._getViewMatrix = function () {
  33068. // Compute
  33069. var cosa = Math.cos(this.alpha);
  33070. var sina = Math.sin(this.alpha);
  33071. var cosb = Math.cos(this.beta);
  33072. var sinb = Math.sin(this.beta);
  33073. if (sinb === 0) {
  33074. sinb = 0.0001;
  33075. }
  33076. var target = this._getTargetPosition();
  33077. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  33078. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  33079. if (!this._collider) {
  33080. this._collider = new BABYLON.Collider();
  33081. }
  33082. this._collider.radius = this.collisionRadius;
  33083. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  33084. this._collisionTriggered = true;
  33085. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  33086. }
  33087. else {
  33088. this.position.copyFrom(this._newPosition);
  33089. var up = this.upVector;
  33090. if (this.allowUpsideDown && sinb < 0) {
  33091. up = up.clone();
  33092. up = up.negate();
  33093. }
  33094. if (this.getScene().useRightHandedSystem) {
  33095. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  33096. }
  33097. else {
  33098. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  33099. }
  33100. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  33101. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  33102. }
  33103. this._currentTarget = target;
  33104. return this._viewMatrix;
  33105. };
  33106. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  33107. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33108. meshes = meshes || this.getScene().meshes;
  33109. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  33110. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  33111. this.radius = distance * this.zoomOnFactor;
  33112. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  33113. };
  33114. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  33115. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  33116. var meshesOrMinMaxVector;
  33117. var distance;
  33118. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  33119. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  33120. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  33121. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  33122. }
  33123. else {
  33124. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  33125. distance = meshesOrMinMaxVectorAndDistance.distance;
  33126. }
  33127. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  33128. if (!doNotUpdateMaxZ) {
  33129. this.maxZ = distance * 2;
  33130. }
  33131. };
  33132. /**
  33133. * @override
  33134. * Override Camera.createRigCamera
  33135. */
  33136. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  33137. var alphaShift;
  33138. switch (this.cameraRigMode) {
  33139. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33140. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33141. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33142. case BABYLON.Camera.RIG_MODE_VR:
  33143. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  33144. break;
  33145. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33146. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  33147. break;
  33148. }
  33149. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  33150. rigCam._cameraRigParams = {};
  33151. return rigCam;
  33152. };
  33153. /**
  33154. * @override
  33155. * Override Camera._updateRigCameras
  33156. */
  33157. ArcRotateCamera.prototype._updateRigCameras = function () {
  33158. var camLeft = this._rigCameras[0];
  33159. var camRight = this._rigCameras[1];
  33160. camLeft.beta = camRight.beta = this.beta;
  33161. camLeft.radius = camRight.radius = this.radius;
  33162. switch (this.cameraRigMode) {
  33163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  33164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  33165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  33166. case BABYLON.Camera.RIG_MODE_VR:
  33167. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33168. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33169. break;
  33170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  33171. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  33172. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  33173. break;
  33174. }
  33175. _super.prototype._updateRigCameras.call(this);
  33176. };
  33177. ArcRotateCamera.prototype.dispose = function () {
  33178. this.inputs.clear();
  33179. _super.prototype.dispose.call(this);
  33180. };
  33181. ArcRotateCamera.prototype.getClassName = function () {
  33182. return "ArcRotateCamera";
  33183. };
  33184. return ArcRotateCamera;
  33185. }(BABYLON.TargetCamera));
  33186. __decorate([
  33187. BABYLON.serialize()
  33188. ], ArcRotateCamera.prototype, "alpha", void 0);
  33189. __decorate([
  33190. BABYLON.serialize()
  33191. ], ArcRotateCamera.prototype, "beta", void 0);
  33192. __decorate([
  33193. BABYLON.serialize()
  33194. ], ArcRotateCamera.prototype, "radius", void 0);
  33195. __decorate([
  33196. BABYLON.serializeAsVector3("target")
  33197. ], ArcRotateCamera.prototype, "_target", void 0);
  33198. __decorate([
  33199. BABYLON.serialize()
  33200. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  33201. __decorate([
  33202. BABYLON.serialize()
  33203. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  33204. __decorate([
  33205. BABYLON.serialize()
  33206. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  33207. __decorate([
  33208. BABYLON.serialize()
  33209. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  33210. __decorate([
  33211. BABYLON.serialize()
  33212. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  33213. __decorate([
  33214. BABYLON.serialize()
  33215. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  33216. __decorate([
  33217. BABYLON.serialize()
  33218. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  33219. __decorate([
  33220. BABYLON.serialize()
  33221. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  33222. __decorate([
  33223. BABYLON.serialize()
  33224. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  33225. __decorate([
  33226. BABYLON.serialize()
  33227. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  33228. __decorate([
  33229. BABYLON.serialize()
  33230. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  33231. __decorate([
  33232. BABYLON.serialize()
  33233. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  33234. __decorate([
  33235. BABYLON.serialize()
  33236. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  33237. __decorate([
  33238. BABYLON.serialize()
  33239. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  33240. BABYLON.ArcRotateCamera = ArcRotateCamera;
  33241. })(BABYLON || (BABYLON = {}));
  33242. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  33243. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  33244. var BABYLON;
  33245. (function (BABYLON) {
  33246. var ArcRotateCameraInputsManager = (function (_super) {
  33247. __extends(ArcRotateCameraInputsManager, _super);
  33248. function ArcRotateCameraInputsManager(camera) {
  33249. return _super.call(this, camera) || this;
  33250. }
  33251. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  33252. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  33253. return this;
  33254. };
  33255. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  33256. this.add(new BABYLON.ArcRotateCameraPointersInput());
  33257. return this;
  33258. };
  33259. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  33260. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  33261. return this;
  33262. };
  33263. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  33264. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  33265. return this;
  33266. };
  33267. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  33268. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  33269. return this;
  33270. };
  33271. return ArcRotateCameraInputsManager;
  33272. }(BABYLON.CameraInputsManager));
  33273. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  33274. })(BABYLON || (BABYLON = {}));
  33275. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  33276. var BABYLON;
  33277. (function (BABYLON) {
  33278. var HemisphericLight = (function (_super) {
  33279. __extends(HemisphericLight, _super);
  33280. /**
  33281. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  33282. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  33283. * The HemisphericLight can't cast shadows.
  33284. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33285. */
  33286. function HemisphericLight(name, direction, scene) {
  33287. var _this = _super.call(this, name, scene) || this;
  33288. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  33289. _this.direction = direction || BABYLON.Vector3.Up();
  33290. return _this;
  33291. }
  33292. HemisphericLight.prototype._buildUniformLayout = function () {
  33293. this._uniformBuffer.addUniform("vLightData", 4);
  33294. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33295. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33296. this._uniformBuffer.addUniform("vLightGround", 3);
  33297. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33298. this._uniformBuffer.create();
  33299. };
  33300. /**
  33301. * Returns the string "HemisphericLight".
  33302. */
  33303. HemisphericLight.prototype.getClassName = function () {
  33304. return "HemisphericLight";
  33305. };
  33306. /**
  33307. * Sets the HemisphericLight direction towards the passed target (Vector3).
  33308. * Returns the updated direction.
  33309. */
  33310. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  33311. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  33312. return this.direction;
  33313. };
  33314. HemisphericLight.prototype.getShadowGenerator = function () {
  33315. return null;
  33316. };
  33317. /**
  33318. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  33319. * Returns the HemisphericLight.
  33320. */
  33321. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  33322. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33323. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  33324. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  33325. return this;
  33326. };
  33327. HemisphericLight.prototype._getWorldMatrix = function () {
  33328. if (!this._worldMatrix) {
  33329. this._worldMatrix = BABYLON.Matrix.Identity();
  33330. }
  33331. return this._worldMatrix;
  33332. };
  33333. /**
  33334. * Returns the integer 3.
  33335. */
  33336. HemisphericLight.prototype.getTypeID = function () {
  33337. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  33338. };
  33339. return HemisphericLight;
  33340. }(BABYLON.Light));
  33341. __decorate([
  33342. BABYLON.serializeAsColor3()
  33343. ], HemisphericLight.prototype, "groundColor", void 0);
  33344. __decorate([
  33345. BABYLON.serializeAsVector3()
  33346. ], HemisphericLight.prototype, "direction", void 0);
  33347. BABYLON.HemisphericLight = HemisphericLight;
  33348. })(BABYLON || (BABYLON = {}));
  33349. //# sourceMappingURL=babylon.hemisphericLight.js.map
  33350. var BABYLON;
  33351. (function (BABYLON) {
  33352. var ShadowLight = (function (_super) {
  33353. __extends(ShadowLight, _super);
  33354. function ShadowLight() {
  33355. var _this = _super !== null && _super.apply(this, arguments) || this;
  33356. _this._needProjectionMatrixCompute = true;
  33357. return _this;
  33358. }
  33359. Object.defineProperty(ShadowLight.prototype, "direction", {
  33360. get: function () {
  33361. return this._direction;
  33362. },
  33363. set: function (value) {
  33364. this._direction = value;
  33365. },
  33366. enumerable: true,
  33367. configurable: true
  33368. });
  33369. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33370. get: function () {
  33371. return this._shadowMinZ;
  33372. },
  33373. set: function (value) {
  33374. this._shadowMinZ = value;
  33375. this.forceProjectionMatrixCompute();
  33376. },
  33377. enumerable: true,
  33378. configurable: true
  33379. });
  33380. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33381. get: function () {
  33382. return this._shadowMaxZ;
  33383. },
  33384. set: function (value) {
  33385. this._shadowMaxZ = value;
  33386. this.forceProjectionMatrixCompute();
  33387. },
  33388. enumerable: true,
  33389. configurable: true
  33390. });
  33391. /**
  33392. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33393. */
  33394. ShadowLight.prototype.computeTransformedInformation = function () {
  33395. if (this.parent && this.parent.getWorldMatrix) {
  33396. if (!this.transformedPosition) {
  33397. this.transformedPosition = BABYLON.Vector3.Zero();
  33398. }
  33399. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33400. // In case the direction is present.
  33401. if (this.direction) {
  33402. if (!this.transformedDirection) {
  33403. this.transformedDirection = BABYLON.Vector3.Zero();
  33404. }
  33405. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33406. }
  33407. return true;
  33408. }
  33409. return false;
  33410. };
  33411. /**
  33412. * Return the depth scale used for the shadow map.
  33413. */
  33414. ShadowLight.prototype.getDepthScale = function () {
  33415. return 30.0;
  33416. };
  33417. /**
  33418. * Returns the light direction (Vector3) for any passed face index.
  33419. */
  33420. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33421. return this.transformedDirection ? this.transformedDirection : this.direction;
  33422. };
  33423. /**
  33424. * Returns the DirectionalLight absolute position in the World.
  33425. */
  33426. ShadowLight.prototype.getAbsolutePosition = function () {
  33427. return this.transformedPosition ? this.transformedPosition : this.position;
  33428. };
  33429. /**
  33430. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33431. * Returns the updated DirectionalLight direction (Vector3).
  33432. */
  33433. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33434. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33435. return this.direction;
  33436. };
  33437. /**
  33438. * Returns the light rotation (Vector3).
  33439. */
  33440. ShadowLight.prototype.getRotation = function () {
  33441. this.direction.normalize();
  33442. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33443. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33444. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33445. };
  33446. /**
  33447. * Boolean : false by default.
  33448. */
  33449. ShadowLight.prototype.needCube = function () {
  33450. return false;
  33451. };
  33452. /**
  33453. * Specifies wether or not the projection matrix should be recomputed this frame.
  33454. */
  33455. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33456. return this._needProjectionMatrixCompute;
  33457. };
  33458. /**
  33459. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33460. */
  33461. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33462. this._needProjectionMatrixCompute = true;
  33463. };
  33464. /**
  33465. * Get the world matrix of the sahdow lights.
  33466. */
  33467. ShadowLight.prototype._getWorldMatrix = function () {
  33468. if (!this._worldMatrix) {
  33469. this._worldMatrix = BABYLON.Matrix.Identity();
  33470. }
  33471. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33472. return this._worldMatrix;
  33473. };
  33474. /**
  33475. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33476. * Returns the light.
  33477. */
  33478. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33479. if (this.customProjectionMatrixBuilder) {
  33480. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33481. }
  33482. else {
  33483. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33484. }
  33485. return this;
  33486. };
  33487. return ShadowLight;
  33488. }(BABYLON.Light));
  33489. __decorate([
  33490. BABYLON.serializeAsVector3()
  33491. ], ShadowLight.prototype, "position", void 0);
  33492. __decorate([
  33493. BABYLON.serializeAsVector3()
  33494. ], ShadowLight.prototype, "direction", null);
  33495. __decorate([
  33496. BABYLON.serialize()
  33497. ], ShadowLight.prototype, "shadowMinZ", null);
  33498. __decorate([
  33499. BABYLON.serialize()
  33500. ], ShadowLight.prototype, "shadowMaxZ", null);
  33501. BABYLON.ShadowLight = ShadowLight;
  33502. })(BABYLON || (BABYLON = {}));
  33503. //# sourceMappingURL=babylon.shadowLight.js.map
  33504. var BABYLON;
  33505. (function (BABYLON) {
  33506. var PointLight = (function (_super) {
  33507. __extends(PointLight, _super);
  33508. /**
  33509. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33510. * A PointLight emits the light in every direction.
  33511. * It can cast shadows.
  33512. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33513. * ```javascript
  33514. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33515. * ```
  33516. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33517. */
  33518. function PointLight(name, position, scene) {
  33519. var _this = _super.call(this, name, scene) || this;
  33520. _this._shadowAngle = Math.PI / 2;
  33521. _this.position = position;
  33522. return _this;
  33523. }
  33524. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33525. /**
  33526. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33527. * This specifies what angle the shadow will use to be created.
  33528. *
  33529. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33530. */
  33531. get: function () {
  33532. return this._shadowAngle;
  33533. },
  33534. /**
  33535. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33536. * This specifies what angle the shadow will use to be created.
  33537. *
  33538. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33539. */
  33540. set: function (value) {
  33541. this._shadowAngle = value;
  33542. this.forceProjectionMatrixCompute();
  33543. },
  33544. enumerable: true,
  33545. configurable: true
  33546. });
  33547. Object.defineProperty(PointLight.prototype, "direction", {
  33548. get: function () {
  33549. return this._direction;
  33550. },
  33551. /**
  33552. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33553. */
  33554. set: function (value) {
  33555. var previousNeedCube = this.needCube();
  33556. this._direction = value;
  33557. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33558. this._shadowGenerator.recreateShadowMap();
  33559. }
  33560. },
  33561. enumerable: true,
  33562. configurable: true
  33563. });
  33564. /**
  33565. * Returns the string "PointLight"
  33566. */
  33567. PointLight.prototype.getClassName = function () {
  33568. return "PointLight";
  33569. };
  33570. /**
  33571. * Returns the integer 0.
  33572. */
  33573. PointLight.prototype.getTypeID = function () {
  33574. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33575. };
  33576. /**
  33577. * Specifies wether or not the shadowmap should be a cube texture.
  33578. */
  33579. PointLight.prototype.needCube = function () {
  33580. return !this.direction;
  33581. };
  33582. /**
  33583. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33584. */
  33585. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33586. if (this.direction) {
  33587. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33588. }
  33589. else {
  33590. switch (faceIndex) {
  33591. case 0:
  33592. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33593. case 1:
  33594. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33595. case 2:
  33596. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33597. case 3:
  33598. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33599. case 4:
  33600. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33601. case 5:
  33602. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33603. }
  33604. }
  33605. return BABYLON.Vector3.Zero();
  33606. };
  33607. /**
  33608. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33609. * - fov = PI / 2
  33610. * - aspect ratio : 1.0
  33611. * - z-near and far equal to the active camera minZ and maxZ.
  33612. * Returns the PointLight.
  33613. */
  33614. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33615. var activeCamera = this.getScene().activeCamera;
  33616. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33617. };
  33618. PointLight.prototype._buildUniformLayout = function () {
  33619. this._uniformBuffer.addUniform("vLightData", 4);
  33620. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33621. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33622. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33623. this._uniformBuffer.create();
  33624. };
  33625. /**
  33626. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  33627. * Returns the PointLight.
  33628. */
  33629. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  33630. if (this.computeTransformedInformation()) {
  33631. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  33632. return this;
  33633. }
  33634. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  33635. return this;
  33636. };
  33637. return PointLight;
  33638. }(BABYLON.ShadowLight));
  33639. __decorate([
  33640. BABYLON.serialize()
  33641. ], PointLight.prototype, "shadowAngle", null);
  33642. BABYLON.PointLight = PointLight;
  33643. })(BABYLON || (BABYLON = {}));
  33644. //# sourceMappingURL=babylon.pointLight.js.map
  33645. /// <reference path="babylon.light.ts" />
  33646. var BABYLON;
  33647. (function (BABYLON) {
  33648. var DirectionalLight = (function (_super) {
  33649. __extends(DirectionalLight, _super);
  33650. /**
  33651. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  33652. * The directional light is emitted from everywhere in the given direction.
  33653. * It can cast shawdows.
  33654. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33655. */
  33656. function DirectionalLight(name, direction, scene) {
  33657. var _this = _super.call(this, name, scene) || this;
  33658. _this._shadowFrustumSize = 0;
  33659. _this._shadowOrthoScale = 0.5;
  33660. _this.autoUpdateExtends = true;
  33661. // Cache
  33662. _this._orthoLeft = Number.MAX_VALUE;
  33663. _this._orthoRight = Number.MIN_VALUE;
  33664. _this._orthoTop = Number.MIN_VALUE;
  33665. _this._orthoBottom = Number.MAX_VALUE;
  33666. _this.position = direction.scale(-1.0);
  33667. _this.direction = direction;
  33668. return _this;
  33669. }
  33670. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  33671. /**
  33672. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  33673. */
  33674. get: function () {
  33675. return this._shadowFrustumSize;
  33676. },
  33677. /**
  33678. * Specifies a fix frustum size for the shadow generation.
  33679. */
  33680. set: function (value) {
  33681. this._shadowFrustumSize = value;
  33682. this.forceProjectionMatrixCompute();
  33683. },
  33684. enumerable: true,
  33685. configurable: true
  33686. });
  33687. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  33688. get: function () {
  33689. return this._shadowOrthoScale;
  33690. },
  33691. set: function (value) {
  33692. this._shadowOrthoScale = value;
  33693. this.forceProjectionMatrixCompute();
  33694. },
  33695. enumerable: true,
  33696. configurable: true
  33697. });
  33698. /**
  33699. * Returns the string "DirectionalLight".
  33700. */
  33701. DirectionalLight.prototype.getClassName = function () {
  33702. return "DirectionalLight";
  33703. };
  33704. /**
  33705. * Returns the integer 1.
  33706. */
  33707. DirectionalLight.prototype.getTypeID = function () {
  33708. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  33709. };
  33710. /**
  33711. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  33712. * Returns the DirectionalLight Shadow projection matrix.
  33713. */
  33714. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33715. if (this.shadowFrustumSize > 0) {
  33716. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  33717. }
  33718. else {
  33719. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33720. }
  33721. };
  33722. /**
  33723. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  33724. * Returns the DirectionalLight Shadow projection matrix.
  33725. */
  33726. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  33727. var activeCamera = this.getScene().activeCamera;
  33728. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33729. };
  33730. /**
  33731. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  33732. * Returns the DirectionalLight Shadow projection matrix.
  33733. */
  33734. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33735. var activeCamera = this.getScene().activeCamera;
  33736. // Check extends
  33737. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  33738. var tempVector3 = BABYLON.Vector3.Zero();
  33739. this._orthoLeft = Number.MAX_VALUE;
  33740. this._orthoRight = Number.MIN_VALUE;
  33741. this._orthoTop = Number.MIN_VALUE;
  33742. this._orthoBottom = Number.MAX_VALUE;
  33743. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  33744. var mesh = renderList[meshIndex];
  33745. if (!mesh) {
  33746. continue;
  33747. }
  33748. var boundingInfo = mesh.getBoundingInfo();
  33749. if (!boundingInfo) {
  33750. continue;
  33751. }
  33752. var boundingBox = boundingInfo.boundingBox;
  33753. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  33754. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  33755. if (tempVector3.x < this._orthoLeft)
  33756. this._orthoLeft = tempVector3.x;
  33757. if (tempVector3.y < this._orthoBottom)
  33758. this._orthoBottom = tempVector3.y;
  33759. if (tempVector3.x > this._orthoRight)
  33760. this._orthoRight = tempVector3.x;
  33761. if (tempVector3.y > this._orthoTop)
  33762. this._orthoTop = tempVector3.y;
  33763. }
  33764. }
  33765. }
  33766. var xOffset = this._orthoRight - this._orthoLeft;
  33767. var yOffset = this._orthoTop - this._orthoBottom;
  33768. 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);
  33769. };
  33770. DirectionalLight.prototype._buildUniformLayout = function () {
  33771. this._uniformBuffer.addUniform("vLightData", 4);
  33772. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33773. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33774. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33775. this._uniformBuffer.create();
  33776. };
  33777. /**
  33778. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  33779. * Returns the DirectionalLight.
  33780. */
  33781. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  33782. if (this.computeTransformedInformation()) {
  33783. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  33784. return this;
  33785. }
  33786. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  33787. return this;
  33788. };
  33789. return DirectionalLight;
  33790. }(BABYLON.ShadowLight));
  33791. __decorate([
  33792. BABYLON.serialize()
  33793. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  33794. __decorate([
  33795. BABYLON.serialize()
  33796. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  33797. __decorate([
  33798. BABYLON.serialize()
  33799. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  33800. BABYLON.DirectionalLight = DirectionalLight;
  33801. })(BABYLON || (BABYLON = {}));
  33802. //# sourceMappingURL=babylon.directionalLight.js.map
  33803. var BABYLON;
  33804. (function (BABYLON) {
  33805. var SpotLight = (function (_super) {
  33806. __extends(SpotLight, _super);
  33807. /**
  33808. * Creates a SpotLight object in the scene with the passed parameters :
  33809. * - `position` (Vector3) is the initial SpotLight position,
  33810. * - `direction` (Vector3) is the initial SpotLight direction,
  33811. * - `angle` (float, in radians) is the spot light cone angle,
  33812. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  33813. * A spot light is a simply light oriented cone.
  33814. * It can cast shadows.
  33815. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33816. */
  33817. function SpotLight(name, position, direction, angle, exponent, scene) {
  33818. var _this = _super.call(this, name, scene) || this;
  33819. _this.position = position;
  33820. _this.direction = direction;
  33821. _this.angle = angle;
  33822. _this.exponent = exponent;
  33823. return _this;
  33824. }
  33825. Object.defineProperty(SpotLight.prototype, "angle", {
  33826. get: function () {
  33827. return this._angle;
  33828. },
  33829. set: function (value) {
  33830. this._angle = value;
  33831. this.forceProjectionMatrixCompute();
  33832. },
  33833. enumerable: true,
  33834. configurable: true
  33835. });
  33836. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  33837. get: function () {
  33838. return this._shadowAngleScale;
  33839. },
  33840. /**
  33841. * Allows scaling the angle of the light for shadow generation only.
  33842. */
  33843. set: function (value) {
  33844. this._shadowAngleScale = value;
  33845. this.forceProjectionMatrixCompute();
  33846. },
  33847. enumerable: true,
  33848. configurable: true
  33849. });
  33850. /**
  33851. * Returns the string "SpotLight".
  33852. */
  33853. SpotLight.prototype.getClassName = function () {
  33854. return "SpotLight";
  33855. };
  33856. /**
  33857. * Returns the integer 2.
  33858. */
  33859. SpotLight.prototype.getTypeID = function () {
  33860. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  33861. };
  33862. /**
  33863. * 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.
  33864. * Returns the SpotLight.
  33865. */
  33866. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33867. var activeCamera = this.getScene().activeCamera;
  33868. this._shadowAngleScale = this._shadowAngleScale || 1;
  33869. var angle = this._shadowAngleScale * this._angle;
  33870. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33871. };
  33872. SpotLight.prototype._buildUniformLayout = function () {
  33873. this._uniformBuffer.addUniform("vLightData", 4);
  33874. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33875. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33876. this._uniformBuffer.addUniform("vLightDirection", 3);
  33877. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33878. this._uniformBuffer.create();
  33879. };
  33880. /**
  33881. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  33882. * Return the SpotLight.
  33883. */
  33884. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  33885. var normalizeDirection;
  33886. if (this.computeTransformedInformation()) {
  33887. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  33888. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  33889. }
  33890. else {
  33891. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  33892. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  33893. }
  33894. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  33895. return this;
  33896. };
  33897. return SpotLight;
  33898. }(BABYLON.ShadowLight));
  33899. __decorate([
  33900. BABYLON.serialize()
  33901. ], SpotLight.prototype, "angle", null);
  33902. __decorate([
  33903. BABYLON.serialize()
  33904. /**
  33905. * Allows scaling the angle of the light for shadow generation only.
  33906. */
  33907. ], SpotLight.prototype, "shadowAngleScale", null);
  33908. __decorate([
  33909. BABYLON.serialize()
  33910. ], SpotLight.prototype, "exponent", void 0);
  33911. BABYLON.SpotLight = SpotLight;
  33912. })(BABYLON || (BABYLON = {}));
  33913. //# sourceMappingURL=babylon.spotLight.js.map
  33914. var BABYLON;
  33915. (function (BABYLON) {
  33916. var AnimationRange = (function () {
  33917. function AnimationRange(name, from, to) {
  33918. this.name = name;
  33919. this.from = from;
  33920. this.to = to;
  33921. }
  33922. AnimationRange.prototype.clone = function () {
  33923. return new AnimationRange(this.name, this.from, this.to);
  33924. };
  33925. return AnimationRange;
  33926. }());
  33927. BABYLON.AnimationRange = AnimationRange;
  33928. /**
  33929. * Composed of a frame, and an action function
  33930. */
  33931. var AnimationEvent = (function () {
  33932. function AnimationEvent(frame, action, onlyOnce) {
  33933. this.frame = frame;
  33934. this.action = action;
  33935. this.onlyOnce = onlyOnce;
  33936. this.isDone = false;
  33937. }
  33938. return AnimationEvent;
  33939. }());
  33940. BABYLON.AnimationEvent = AnimationEvent;
  33941. var PathCursor = (function () {
  33942. function PathCursor(path) {
  33943. this.path = path;
  33944. this._onchange = new Array();
  33945. this.value = 0;
  33946. this.animations = new Array();
  33947. }
  33948. PathCursor.prototype.getPoint = function () {
  33949. var point = this.path.getPointAtLengthPosition(this.value);
  33950. return new BABYLON.Vector3(point.x, 0, point.y);
  33951. };
  33952. PathCursor.prototype.moveAhead = function (step) {
  33953. if (step === void 0) { step = 0.002; }
  33954. this.move(step);
  33955. return this;
  33956. };
  33957. PathCursor.prototype.moveBack = function (step) {
  33958. if (step === void 0) { step = 0.002; }
  33959. this.move(-step);
  33960. return this;
  33961. };
  33962. PathCursor.prototype.move = function (step) {
  33963. if (Math.abs(step) > 1) {
  33964. throw "step size should be less than 1.";
  33965. }
  33966. this.value += step;
  33967. this.ensureLimits();
  33968. this.raiseOnChange();
  33969. return this;
  33970. };
  33971. PathCursor.prototype.ensureLimits = function () {
  33972. while (this.value > 1) {
  33973. this.value -= 1;
  33974. }
  33975. while (this.value < 0) {
  33976. this.value += 1;
  33977. }
  33978. return this;
  33979. };
  33980. // used by animation engine
  33981. PathCursor.prototype.markAsDirty = function (propertyName) {
  33982. this.ensureLimits();
  33983. this.raiseOnChange();
  33984. return this;
  33985. };
  33986. PathCursor.prototype.raiseOnChange = function () {
  33987. var _this = this;
  33988. this._onchange.forEach(function (f) { return f(_this); });
  33989. return this;
  33990. };
  33991. PathCursor.prototype.onchange = function (f) {
  33992. this._onchange.push(f);
  33993. return this;
  33994. };
  33995. return PathCursor;
  33996. }());
  33997. BABYLON.PathCursor = PathCursor;
  33998. var Animation = (function () {
  33999. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  34000. this.name = name;
  34001. this.targetProperty = targetProperty;
  34002. this.framePerSecond = framePerSecond;
  34003. this.dataType = dataType;
  34004. this.loopMode = loopMode;
  34005. this.enableBlending = enableBlending;
  34006. this._offsetsCache = {};
  34007. this._highLimitsCache = {};
  34008. this._stopped = false;
  34009. this._blendingFactor = 0;
  34010. // The set of event that will be linked to this animation
  34011. this._events = new Array();
  34012. this.allowMatricesInterpolation = false;
  34013. this.blendingSpeed = 0.01;
  34014. this._ranges = {};
  34015. this.targetPropertyPath = targetProperty.split(".");
  34016. this.dataType = dataType;
  34017. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  34018. }
  34019. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  34020. var dataType = undefined;
  34021. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  34022. dataType = Animation.ANIMATIONTYPE_FLOAT;
  34023. }
  34024. else if (from instanceof BABYLON.Quaternion) {
  34025. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  34026. }
  34027. else if (from instanceof BABYLON.Vector3) {
  34028. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  34029. }
  34030. else if (from instanceof BABYLON.Vector2) {
  34031. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  34032. }
  34033. else if (from instanceof BABYLON.Color3) {
  34034. dataType = Animation.ANIMATIONTYPE_COLOR3;
  34035. }
  34036. else if (from instanceof BABYLON.Size) {
  34037. dataType = Animation.ANIMATIONTYPE_SIZE;
  34038. }
  34039. if (dataType == undefined) {
  34040. return null;
  34041. }
  34042. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  34043. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  34044. animation.setKeys(keys);
  34045. if (easingFunction !== undefined) {
  34046. animation.setEasingFunction(easingFunction);
  34047. }
  34048. return animation;
  34049. };
  34050. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34051. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34052. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34053. };
  34054. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  34055. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  34056. node.animations.push(animation);
  34057. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  34058. };
  34059. // Methods
  34060. /**
  34061. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34062. */
  34063. Animation.prototype.toString = function (fullDetails) {
  34064. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  34065. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  34066. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  34067. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34068. if (fullDetails) {
  34069. ret += ", Ranges: {";
  34070. var first = true;
  34071. for (var name in this._ranges) {
  34072. if (first) {
  34073. ret += ", ";
  34074. first = false;
  34075. }
  34076. ret += name;
  34077. }
  34078. ret += "}";
  34079. }
  34080. return ret;
  34081. };
  34082. /**
  34083. * Add an event to this animation.
  34084. */
  34085. Animation.prototype.addEvent = function (event) {
  34086. this._events.push(event);
  34087. };
  34088. /**
  34089. * Remove all events found at the given frame
  34090. * @param frame
  34091. */
  34092. Animation.prototype.removeEvents = function (frame) {
  34093. for (var index = 0; index < this._events.length; index++) {
  34094. if (this._events[index].frame === frame) {
  34095. this._events.splice(index, 1);
  34096. index--;
  34097. }
  34098. }
  34099. };
  34100. Animation.prototype.createRange = function (name, from, to) {
  34101. // check name not already in use; could happen for bones after serialized
  34102. if (!this._ranges[name]) {
  34103. this._ranges[name] = new AnimationRange(name, from, to);
  34104. }
  34105. };
  34106. Animation.prototype.deleteRange = function (name, deleteFrames) {
  34107. if (deleteFrames === void 0) { deleteFrames = true; }
  34108. if (this._ranges[name]) {
  34109. if (deleteFrames) {
  34110. var from = this._ranges[name].from;
  34111. var to = this._ranges[name].to;
  34112. // this loop MUST go high to low for multiple splices to work
  34113. for (var key = this._keys.length - 1; key >= 0; key--) {
  34114. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  34115. this._keys.splice(key, 1);
  34116. }
  34117. }
  34118. }
  34119. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34120. }
  34121. };
  34122. Animation.prototype.getRange = function (name) {
  34123. return this._ranges[name];
  34124. };
  34125. Animation.prototype.reset = function () {
  34126. this._offsetsCache = {};
  34127. this._highLimitsCache = {};
  34128. this.currentFrame = 0;
  34129. this._blendingFactor = 0;
  34130. this._originalBlendValue = null;
  34131. };
  34132. Animation.prototype.isStopped = function () {
  34133. return this._stopped;
  34134. };
  34135. Animation.prototype.getKeys = function () {
  34136. return this._keys;
  34137. };
  34138. Animation.prototype.getHighestFrame = function () {
  34139. var ret = 0;
  34140. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  34141. if (ret < this._keys[key].frame) {
  34142. ret = this._keys[key].frame;
  34143. }
  34144. }
  34145. return ret;
  34146. };
  34147. Animation.prototype.getEasingFunction = function () {
  34148. return this._easingFunction;
  34149. };
  34150. Animation.prototype.setEasingFunction = function (easingFunction) {
  34151. this._easingFunction = easingFunction;
  34152. };
  34153. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  34154. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  34155. };
  34156. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34157. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34158. };
  34159. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  34160. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  34161. };
  34162. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34163. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  34164. };
  34165. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  34166. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  34167. };
  34168. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34169. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34170. };
  34171. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  34172. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  34173. };
  34174. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  34175. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  34176. };
  34177. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  34178. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  34179. };
  34180. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  34181. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  34182. };
  34183. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  34184. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  34185. };
  34186. Animation.prototype.clone = function () {
  34187. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  34188. clone.enableBlending = this.enableBlending;
  34189. clone.blendingSpeed = this.blendingSpeed;
  34190. if (this._keys) {
  34191. clone.setKeys(this._keys);
  34192. }
  34193. if (this._ranges) {
  34194. clone._ranges = {};
  34195. for (var name in this._ranges) {
  34196. clone._ranges[name] = this._ranges[name].clone();
  34197. }
  34198. }
  34199. return clone;
  34200. };
  34201. Animation.prototype.setKeys = function (values) {
  34202. this._keys = values.slice(0);
  34203. this._offsetsCache = {};
  34204. this._highLimitsCache = {};
  34205. };
  34206. Animation.prototype._getKeyValue = function (value) {
  34207. if (typeof value === "function") {
  34208. return value();
  34209. }
  34210. return value;
  34211. };
  34212. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  34213. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  34214. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  34215. }
  34216. this.currentFrame = currentFrame;
  34217. // Try to get a hash to find the right key
  34218. 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));
  34219. if (this._keys[startKeyIndex].frame >= currentFrame) {
  34220. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  34221. startKeyIndex--;
  34222. }
  34223. }
  34224. for (var key = startKeyIndex; key < this._keys.length; key++) {
  34225. var endKey = this._keys[key + 1];
  34226. if (endKey.frame >= currentFrame) {
  34227. var startKey = this._keys[key];
  34228. var startValue = this._getKeyValue(startKey.value);
  34229. var endValue = this._getKeyValue(endKey.value);
  34230. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  34231. var frameDelta = endKey.frame - startKey.frame;
  34232. // gradient : percent of currentFrame between the frame inf and the frame sup
  34233. var gradient = (currentFrame - startKey.frame) / frameDelta;
  34234. // check for easingFunction and correction of gradient
  34235. if (this._easingFunction != null) {
  34236. gradient = this._easingFunction.ease(gradient);
  34237. }
  34238. switch (this.dataType) {
  34239. // Float
  34240. case Animation.ANIMATIONTYPE_FLOAT:
  34241. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  34242. switch (loopMode) {
  34243. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34244. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34245. return floatValue;
  34246. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34247. return offsetValue * repeatCount + floatValue;
  34248. }
  34249. break;
  34250. // Quaternion
  34251. case Animation.ANIMATIONTYPE_QUATERNION:
  34252. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  34253. switch (loopMode) {
  34254. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34255. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34256. return quatValue;
  34257. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34258. return quatValue.add(offsetValue.scale(repeatCount));
  34259. }
  34260. return quatValue;
  34261. // Vector3
  34262. case Animation.ANIMATIONTYPE_VECTOR3:
  34263. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  34264. switch (loopMode) {
  34265. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34266. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34267. return vec3Value;
  34268. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34269. return vec3Value.add(offsetValue.scale(repeatCount));
  34270. }
  34271. // Vector2
  34272. case Animation.ANIMATIONTYPE_VECTOR2:
  34273. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  34274. switch (loopMode) {
  34275. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34276. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34277. return vec2Value;
  34278. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34279. return vec2Value.add(offsetValue.scale(repeatCount));
  34280. }
  34281. // Size
  34282. case Animation.ANIMATIONTYPE_SIZE:
  34283. switch (loopMode) {
  34284. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34285. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34286. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  34287. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34288. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34289. }
  34290. // Color3
  34291. case Animation.ANIMATIONTYPE_COLOR3:
  34292. switch (loopMode) {
  34293. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34294. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34295. return this.color3InterpolateFunction(startValue, endValue, gradient);
  34296. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34297. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  34298. }
  34299. // Matrix
  34300. case Animation.ANIMATIONTYPE_MATRIX:
  34301. switch (loopMode) {
  34302. case Animation.ANIMATIONLOOPMODE_CYCLE:
  34303. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  34304. if (this.allowMatricesInterpolation) {
  34305. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  34306. }
  34307. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  34308. return startValue;
  34309. }
  34310. default:
  34311. break;
  34312. }
  34313. break;
  34314. }
  34315. }
  34316. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  34317. };
  34318. Animation.prototype.setValue = function (currentValue, blend) {
  34319. if (blend === void 0) { blend = false; }
  34320. // Set value
  34321. var path;
  34322. var destination;
  34323. if (this.targetPropertyPath.length > 1) {
  34324. var property = this._target[this.targetPropertyPath[0]];
  34325. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  34326. property = property[this.targetPropertyPath[index]];
  34327. }
  34328. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  34329. destination = property;
  34330. }
  34331. else {
  34332. path = this.targetPropertyPath[0];
  34333. destination = this._target;
  34334. }
  34335. // Blending
  34336. if (this.enableBlending && this._blendingFactor <= 1.0) {
  34337. if (!this._originalBlendValue) {
  34338. if (destination[path].clone) {
  34339. this._originalBlendValue = destination[path].clone();
  34340. }
  34341. else {
  34342. this._originalBlendValue = destination[path];
  34343. }
  34344. }
  34345. if (this._originalBlendValue.prototype) {
  34346. if (this._originalBlendValue.prototype.Lerp) {
  34347. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  34348. }
  34349. else {
  34350. destination[path] = currentValue;
  34351. }
  34352. }
  34353. else if (this._originalBlendValue.m) {
  34354. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  34355. }
  34356. else {
  34357. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  34358. }
  34359. this._blendingFactor += this.blendingSpeed;
  34360. }
  34361. else {
  34362. destination[path] = currentValue;
  34363. }
  34364. if (this._target.markAsDirty) {
  34365. this._target.markAsDirty(this.targetProperty);
  34366. }
  34367. };
  34368. Animation.prototype.goToFrame = function (frame) {
  34369. if (frame < this._keys[0].frame) {
  34370. frame = this._keys[0].frame;
  34371. }
  34372. else if (frame > this._keys[this._keys.length - 1].frame) {
  34373. frame = this._keys[this._keys.length - 1].frame;
  34374. }
  34375. var currentValue = this._interpolate(frame, 0, this.loopMode);
  34376. this.setValue(currentValue);
  34377. };
  34378. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  34379. if (blend === void 0) { blend = false; }
  34380. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  34381. this._stopped = true;
  34382. return false;
  34383. }
  34384. var returnValue = true;
  34385. // Adding a start key at frame 0 if missing
  34386. if (this._keys[0].frame !== 0) {
  34387. var newKey = { frame: 0, value: this._keys[0].value };
  34388. this._keys.splice(0, 0, newKey);
  34389. }
  34390. // Check limits
  34391. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  34392. from = this._keys[0].frame;
  34393. }
  34394. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  34395. to = this._keys[this._keys.length - 1].frame;
  34396. }
  34397. //to and from cannot be the same key
  34398. if (from === to) {
  34399. from++;
  34400. }
  34401. // Compute ratio
  34402. var range = to - from;
  34403. var offsetValue;
  34404. // ratio represents the frame delta between from and to
  34405. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  34406. var highLimitValue = 0;
  34407. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  34408. returnValue = false;
  34409. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  34410. }
  34411. else {
  34412. // Get max value if required
  34413. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  34414. var keyOffset = to.toString() + from.toString();
  34415. if (!this._offsetsCache[keyOffset]) {
  34416. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34417. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  34418. switch (this.dataType) {
  34419. // Float
  34420. case Animation.ANIMATIONTYPE_FLOAT:
  34421. this._offsetsCache[keyOffset] = toValue - fromValue;
  34422. break;
  34423. // Quaternion
  34424. case Animation.ANIMATIONTYPE_QUATERNION:
  34425. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34426. break;
  34427. // Vector3
  34428. case Animation.ANIMATIONTYPE_VECTOR3:
  34429. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34430. // Vector2
  34431. case Animation.ANIMATIONTYPE_VECTOR2:
  34432. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34433. // Size
  34434. case Animation.ANIMATIONTYPE_SIZE:
  34435. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34436. // Color3
  34437. case Animation.ANIMATIONTYPE_COLOR3:
  34438. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  34439. default:
  34440. break;
  34441. }
  34442. this._highLimitsCache[keyOffset] = toValue;
  34443. }
  34444. highLimitValue = this._highLimitsCache[keyOffset];
  34445. offsetValue = this._offsetsCache[keyOffset];
  34446. }
  34447. }
  34448. if (offsetValue === undefined) {
  34449. switch (this.dataType) {
  34450. // Float
  34451. case Animation.ANIMATIONTYPE_FLOAT:
  34452. offsetValue = 0;
  34453. break;
  34454. // Quaternion
  34455. case Animation.ANIMATIONTYPE_QUATERNION:
  34456. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  34457. break;
  34458. // Vector3
  34459. case Animation.ANIMATIONTYPE_VECTOR3:
  34460. offsetValue = BABYLON.Vector3.Zero();
  34461. break;
  34462. // Vector2
  34463. case Animation.ANIMATIONTYPE_VECTOR2:
  34464. offsetValue = BABYLON.Vector2.Zero();
  34465. break;
  34466. // Size
  34467. case Animation.ANIMATIONTYPE_SIZE:
  34468. offsetValue = BABYLON.Size.Zero();
  34469. break;
  34470. // Color3
  34471. case Animation.ANIMATIONTYPE_COLOR3:
  34472. offsetValue = BABYLON.Color3.Black();
  34473. }
  34474. }
  34475. // Compute value
  34476. var repeatCount = (ratio / range) >> 0;
  34477. var currentFrame = returnValue ? from + ratio % range : to;
  34478. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  34479. // Set value
  34480. this.setValue(currentValue);
  34481. // Check events
  34482. for (var index = 0; index < this._events.length; index++) {
  34483. if (currentFrame >= this._events[index].frame) {
  34484. var event = this._events[index];
  34485. if (!event.isDone) {
  34486. // If event should be done only once, remove it.
  34487. if (event.onlyOnce) {
  34488. this._events.splice(index, 1);
  34489. index--;
  34490. }
  34491. event.isDone = true;
  34492. event.action();
  34493. } // Don't do anything if the event has already be done.
  34494. }
  34495. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  34496. // reset event, the animation is looping
  34497. this._events[index].isDone = false;
  34498. }
  34499. }
  34500. if (!returnValue) {
  34501. this._stopped = true;
  34502. }
  34503. return returnValue;
  34504. };
  34505. Animation.prototype.serialize = function () {
  34506. var serializationObject = {};
  34507. serializationObject.name = this.name;
  34508. serializationObject.property = this.targetProperty;
  34509. serializationObject.framePerSecond = this.framePerSecond;
  34510. serializationObject.dataType = this.dataType;
  34511. serializationObject.loopBehavior = this.loopMode;
  34512. serializationObject.enableBlending = this.enableBlending;
  34513. serializationObject.blendingSpeed = this.blendingSpeed;
  34514. var dataType = this.dataType;
  34515. serializationObject.keys = [];
  34516. var keys = this.getKeys();
  34517. for (var index = 0; index < keys.length; index++) {
  34518. var animationKey = keys[index];
  34519. var key = {};
  34520. key.frame = animationKey.frame;
  34521. switch (dataType) {
  34522. case Animation.ANIMATIONTYPE_FLOAT:
  34523. key.values = [animationKey.value];
  34524. break;
  34525. case Animation.ANIMATIONTYPE_QUATERNION:
  34526. case Animation.ANIMATIONTYPE_MATRIX:
  34527. case Animation.ANIMATIONTYPE_VECTOR3:
  34528. case Animation.ANIMATIONTYPE_COLOR3:
  34529. key.values = animationKey.value.asArray();
  34530. break;
  34531. }
  34532. serializationObject.keys.push(key);
  34533. }
  34534. serializationObject.ranges = [];
  34535. for (var name in this._ranges) {
  34536. var range = {};
  34537. range.name = name;
  34538. range.from = this._ranges[name].from;
  34539. range.to = this._ranges[name].to;
  34540. serializationObject.ranges.push(range);
  34541. }
  34542. return serializationObject;
  34543. };
  34544. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  34545. get: function () {
  34546. return Animation._ANIMATIONTYPE_FLOAT;
  34547. },
  34548. enumerable: true,
  34549. configurable: true
  34550. });
  34551. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  34552. get: function () {
  34553. return Animation._ANIMATIONTYPE_VECTOR3;
  34554. },
  34555. enumerable: true,
  34556. configurable: true
  34557. });
  34558. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  34559. get: function () {
  34560. return Animation._ANIMATIONTYPE_VECTOR2;
  34561. },
  34562. enumerable: true,
  34563. configurable: true
  34564. });
  34565. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  34566. get: function () {
  34567. return Animation._ANIMATIONTYPE_SIZE;
  34568. },
  34569. enumerable: true,
  34570. configurable: true
  34571. });
  34572. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  34573. get: function () {
  34574. return Animation._ANIMATIONTYPE_QUATERNION;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  34580. get: function () {
  34581. return Animation._ANIMATIONTYPE_MATRIX;
  34582. },
  34583. enumerable: true,
  34584. configurable: true
  34585. });
  34586. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  34587. get: function () {
  34588. return Animation._ANIMATIONTYPE_COLOR3;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  34594. get: function () {
  34595. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  34596. },
  34597. enumerable: true,
  34598. configurable: true
  34599. });
  34600. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  34601. get: function () {
  34602. return Animation._ANIMATIONLOOPMODE_CYCLE;
  34603. },
  34604. enumerable: true,
  34605. configurable: true
  34606. });
  34607. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  34608. get: function () {
  34609. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  34610. },
  34611. enumerable: true,
  34612. configurable: true
  34613. });
  34614. Animation.Parse = function (parsedAnimation) {
  34615. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  34616. var dataType = parsedAnimation.dataType;
  34617. var keys = [];
  34618. var data;
  34619. var index;
  34620. if (parsedAnimation.enableBlending) {
  34621. animation.enableBlending = parsedAnimation.enableBlending;
  34622. }
  34623. if (parsedAnimation.blendingSpeed) {
  34624. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  34625. }
  34626. for (index = 0; index < parsedAnimation.keys.length; index++) {
  34627. var key = parsedAnimation.keys[index];
  34628. switch (dataType) {
  34629. case Animation.ANIMATIONTYPE_FLOAT:
  34630. data = key.values[0];
  34631. break;
  34632. case Animation.ANIMATIONTYPE_QUATERNION:
  34633. data = BABYLON.Quaternion.FromArray(key.values);
  34634. break;
  34635. case Animation.ANIMATIONTYPE_MATRIX:
  34636. data = BABYLON.Matrix.FromArray(key.values);
  34637. break;
  34638. case Animation.ANIMATIONTYPE_COLOR3:
  34639. data = BABYLON.Color3.FromArray(key.values);
  34640. break;
  34641. case Animation.ANIMATIONTYPE_VECTOR3:
  34642. default:
  34643. data = BABYLON.Vector3.FromArray(key.values);
  34644. break;
  34645. }
  34646. keys.push({
  34647. frame: key.frame,
  34648. value: data
  34649. });
  34650. }
  34651. animation.setKeys(keys);
  34652. if (parsedAnimation.ranges) {
  34653. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  34654. data = parsedAnimation.ranges[index];
  34655. animation.createRange(data.name, data.from, data.to);
  34656. }
  34657. }
  34658. return animation;
  34659. };
  34660. Animation.AppendSerializedAnimations = function (source, destination) {
  34661. if (source.animations) {
  34662. destination.animations = [];
  34663. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  34664. var animation = source.animations[animationIndex];
  34665. destination.animations.push(animation.serialize());
  34666. }
  34667. }
  34668. };
  34669. return Animation;
  34670. }());
  34671. // Statics
  34672. Animation._ANIMATIONTYPE_FLOAT = 0;
  34673. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  34674. Animation._ANIMATIONTYPE_QUATERNION = 2;
  34675. Animation._ANIMATIONTYPE_MATRIX = 3;
  34676. Animation._ANIMATIONTYPE_COLOR3 = 4;
  34677. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  34678. Animation._ANIMATIONTYPE_SIZE = 6;
  34679. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  34680. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  34681. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  34682. BABYLON.Animation = Animation;
  34683. })(BABYLON || (BABYLON = {}));
  34684. //# sourceMappingURL=babylon.animation.js.map
  34685. var BABYLON;
  34686. (function (BABYLON) {
  34687. var Animatable = (function () {
  34688. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  34689. if (fromFrame === void 0) { fromFrame = 0; }
  34690. if (toFrame === void 0) { toFrame = 100; }
  34691. if (loopAnimation === void 0) { loopAnimation = false; }
  34692. if (speedRatio === void 0) { speedRatio = 1.0; }
  34693. this.target = target;
  34694. this.fromFrame = fromFrame;
  34695. this.toFrame = toFrame;
  34696. this.loopAnimation = loopAnimation;
  34697. this.speedRatio = speedRatio;
  34698. this.onAnimationEnd = onAnimationEnd;
  34699. this._localDelayOffset = null;
  34700. this._pausedDelay = null;
  34701. this._animations = new Array();
  34702. this._paused = false;
  34703. this.animationStarted = false;
  34704. if (animations) {
  34705. this.appendAnimations(target, animations);
  34706. }
  34707. this._scene = scene;
  34708. scene._activeAnimatables.push(this);
  34709. }
  34710. // Methods
  34711. Animatable.prototype.getAnimations = function () {
  34712. return this._animations;
  34713. };
  34714. Animatable.prototype.appendAnimations = function (target, animations) {
  34715. for (var index = 0; index < animations.length; index++) {
  34716. var animation = animations[index];
  34717. animation._target = target;
  34718. this._animations.push(animation);
  34719. }
  34720. };
  34721. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  34722. var animations = this._animations;
  34723. for (var index = 0; index < animations.length; index++) {
  34724. if (animations[index].targetProperty === property) {
  34725. return animations[index];
  34726. }
  34727. }
  34728. return null;
  34729. };
  34730. Animatable.prototype.reset = function () {
  34731. var animations = this._animations;
  34732. for (var index = 0; index < animations.length; index++) {
  34733. animations[index].reset();
  34734. }
  34735. this._localDelayOffset = null;
  34736. this._pausedDelay = null;
  34737. };
  34738. Animatable.prototype.enableBlending = function (blendingSpeed) {
  34739. var animations = this._animations;
  34740. for (var index = 0; index < animations.length; index++) {
  34741. animations[index].enableBlending = true;
  34742. animations[index].blendingSpeed = blendingSpeed;
  34743. }
  34744. };
  34745. Animatable.prototype.disableBlending = function () {
  34746. var animations = this._animations;
  34747. for (var index = 0; index < animations.length; index++) {
  34748. animations[index].enableBlending = false;
  34749. }
  34750. };
  34751. Animatable.prototype.goToFrame = function (frame) {
  34752. var animations = this._animations;
  34753. if (animations[0]) {
  34754. var fps = animations[0].framePerSecond;
  34755. var currentFrame = animations[0].currentFrame;
  34756. var adjustTime = frame - currentFrame;
  34757. var delay = adjustTime * 1000 / fps;
  34758. this._localDelayOffset -= delay;
  34759. }
  34760. for (var index = 0; index < animations.length; index++) {
  34761. animations[index].goToFrame(frame);
  34762. }
  34763. };
  34764. Animatable.prototype.pause = function () {
  34765. if (this._paused) {
  34766. return;
  34767. }
  34768. this._paused = true;
  34769. };
  34770. Animatable.prototype.restart = function () {
  34771. this._paused = false;
  34772. };
  34773. Animatable.prototype.stop = function (animationName) {
  34774. if (animationName) {
  34775. var idx = this._scene._activeAnimatables.indexOf(this);
  34776. if (idx > -1) {
  34777. var animations = this._animations;
  34778. for (var index = animations.length - 1; index >= 0; index--) {
  34779. if (typeof animationName === "string" && animations[index].name != animationName) {
  34780. continue;
  34781. }
  34782. animations[index].reset();
  34783. animations.splice(index, 1);
  34784. }
  34785. if (animations.length == 0) {
  34786. this._scene._activeAnimatables.splice(idx, 1);
  34787. if (this.onAnimationEnd) {
  34788. this.onAnimationEnd();
  34789. }
  34790. }
  34791. }
  34792. }
  34793. else {
  34794. var index = this._scene._activeAnimatables.indexOf(this);
  34795. if (index > -1) {
  34796. this._scene._activeAnimatables.splice(index, 1);
  34797. var animations = this._animations;
  34798. for (var index = 0; index < animations.length; index++) {
  34799. animations[index].reset();
  34800. }
  34801. if (this.onAnimationEnd) {
  34802. this.onAnimationEnd();
  34803. }
  34804. }
  34805. }
  34806. };
  34807. Animatable.prototype._animate = function (delay) {
  34808. if (this._paused) {
  34809. this.animationStarted = false;
  34810. if (this._pausedDelay === null) {
  34811. this._pausedDelay = delay;
  34812. }
  34813. return true;
  34814. }
  34815. if (this._localDelayOffset === null) {
  34816. this._localDelayOffset = delay;
  34817. }
  34818. else if (this._pausedDelay !== null) {
  34819. this._localDelayOffset += delay - this._pausedDelay;
  34820. this._pausedDelay = null;
  34821. }
  34822. // Animating
  34823. var running = false;
  34824. var animations = this._animations;
  34825. var index;
  34826. for (index = 0; index < animations.length; index++) {
  34827. var animation = animations[index];
  34828. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  34829. running = running || isRunning;
  34830. }
  34831. this.animationStarted = running;
  34832. if (!running) {
  34833. // Remove from active animatables
  34834. index = this._scene._activeAnimatables.indexOf(this);
  34835. this._scene._activeAnimatables.splice(index, 1);
  34836. }
  34837. if (!running && this.onAnimationEnd) {
  34838. this.onAnimationEnd();
  34839. this.onAnimationEnd = null;
  34840. }
  34841. return running;
  34842. };
  34843. return Animatable;
  34844. }());
  34845. BABYLON.Animatable = Animatable;
  34846. })(BABYLON || (BABYLON = {}));
  34847. //# sourceMappingURL=babylon.animatable.js.map
  34848. var BABYLON;
  34849. (function (BABYLON) {
  34850. var EasingFunction = (function () {
  34851. function EasingFunction() {
  34852. // Properties
  34853. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  34854. }
  34855. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  34856. get: function () {
  34857. return EasingFunction._EASINGMODE_EASEIN;
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  34863. get: function () {
  34864. return EasingFunction._EASINGMODE_EASEOUT;
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  34870. get: function () {
  34871. return EasingFunction._EASINGMODE_EASEINOUT;
  34872. },
  34873. enumerable: true,
  34874. configurable: true
  34875. });
  34876. EasingFunction.prototype.setEasingMode = function (easingMode) {
  34877. var n = Math.min(Math.max(easingMode, 0), 2);
  34878. this._easingMode = n;
  34879. };
  34880. EasingFunction.prototype.getEasingMode = function () {
  34881. return this._easingMode;
  34882. };
  34883. EasingFunction.prototype.easeInCore = function (gradient) {
  34884. throw new Error('You must implement this method');
  34885. };
  34886. EasingFunction.prototype.ease = function (gradient) {
  34887. switch (this._easingMode) {
  34888. case EasingFunction.EASINGMODE_EASEIN:
  34889. return this.easeInCore(gradient);
  34890. case EasingFunction.EASINGMODE_EASEOUT:
  34891. return (1 - this.easeInCore(1 - gradient));
  34892. }
  34893. if (gradient >= 0.5) {
  34894. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  34895. }
  34896. return (this.easeInCore(gradient * 2) * 0.5);
  34897. };
  34898. return EasingFunction;
  34899. }());
  34900. //Statics
  34901. EasingFunction._EASINGMODE_EASEIN = 0;
  34902. EasingFunction._EASINGMODE_EASEOUT = 1;
  34903. EasingFunction._EASINGMODE_EASEINOUT = 2;
  34904. BABYLON.EasingFunction = EasingFunction;
  34905. var CircleEase = (function (_super) {
  34906. __extends(CircleEase, _super);
  34907. function CircleEase() {
  34908. return _super !== null && _super.apply(this, arguments) || this;
  34909. }
  34910. CircleEase.prototype.easeInCore = function (gradient) {
  34911. gradient = Math.max(0, Math.min(1, gradient));
  34912. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  34913. };
  34914. return CircleEase;
  34915. }(EasingFunction));
  34916. BABYLON.CircleEase = CircleEase;
  34917. var BackEase = (function (_super) {
  34918. __extends(BackEase, _super);
  34919. function BackEase(amplitude) {
  34920. if (amplitude === void 0) { amplitude = 1; }
  34921. var _this = _super.call(this) || this;
  34922. _this.amplitude = amplitude;
  34923. return _this;
  34924. }
  34925. BackEase.prototype.easeInCore = function (gradient) {
  34926. var num = Math.max(0, this.amplitude);
  34927. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  34928. };
  34929. return BackEase;
  34930. }(EasingFunction));
  34931. BABYLON.BackEase = BackEase;
  34932. var BounceEase = (function (_super) {
  34933. __extends(BounceEase, _super);
  34934. function BounceEase(bounces, bounciness) {
  34935. if (bounces === void 0) { bounces = 3; }
  34936. if (bounciness === void 0) { bounciness = 2; }
  34937. var _this = _super.call(this) || this;
  34938. _this.bounces = bounces;
  34939. _this.bounciness = bounciness;
  34940. return _this;
  34941. }
  34942. BounceEase.prototype.easeInCore = function (gradient) {
  34943. var y = Math.max(0.0, this.bounces);
  34944. var bounciness = this.bounciness;
  34945. if (bounciness <= 1.0) {
  34946. bounciness = 1.001;
  34947. }
  34948. var num9 = Math.pow(bounciness, y);
  34949. var num5 = 1.0 - bounciness;
  34950. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  34951. var num15 = gradient * num4;
  34952. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  34953. var num3 = Math.floor(num65);
  34954. var num13 = num3 + 1.0;
  34955. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  34956. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  34957. var num7 = (num8 + num12) * 0.5;
  34958. var num6 = gradient - num7;
  34959. var num2 = num7 - num8;
  34960. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  34961. };
  34962. return BounceEase;
  34963. }(EasingFunction));
  34964. BABYLON.BounceEase = BounceEase;
  34965. var CubicEase = (function (_super) {
  34966. __extends(CubicEase, _super);
  34967. function CubicEase() {
  34968. return _super !== null && _super.apply(this, arguments) || this;
  34969. }
  34970. CubicEase.prototype.easeInCore = function (gradient) {
  34971. return (gradient * gradient * gradient);
  34972. };
  34973. return CubicEase;
  34974. }(EasingFunction));
  34975. BABYLON.CubicEase = CubicEase;
  34976. var ElasticEase = (function (_super) {
  34977. __extends(ElasticEase, _super);
  34978. function ElasticEase(oscillations, springiness) {
  34979. if (oscillations === void 0) { oscillations = 3; }
  34980. if (springiness === void 0) { springiness = 3; }
  34981. var _this = _super.call(this) || this;
  34982. _this.oscillations = oscillations;
  34983. _this.springiness = springiness;
  34984. return _this;
  34985. }
  34986. ElasticEase.prototype.easeInCore = function (gradient) {
  34987. var num2;
  34988. var num3 = Math.max(0.0, this.oscillations);
  34989. var num = Math.max(0.0, this.springiness);
  34990. if (num == 0) {
  34991. num2 = gradient;
  34992. }
  34993. else {
  34994. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  34995. }
  34996. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  34997. };
  34998. return ElasticEase;
  34999. }(EasingFunction));
  35000. BABYLON.ElasticEase = ElasticEase;
  35001. var ExponentialEase = (function (_super) {
  35002. __extends(ExponentialEase, _super);
  35003. function ExponentialEase(exponent) {
  35004. if (exponent === void 0) { exponent = 2; }
  35005. var _this = _super.call(this) || this;
  35006. _this.exponent = exponent;
  35007. return _this;
  35008. }
  35009. ExponentialEase.prototype.easeInCore = function (gradient) {
  35010. if (this.exponent <= 0) {
  35011. return gradient;
  35012. }
  35013. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  35014. };
  35015. return ExponentialEase;
  35016. }(EasingFunction));
  35017. BABYLON.ExponentialEase = ExponentialEase;
  35018. var PowerEase = (function (_super) {
  35019. __extends(PowerEase, _super);
  35020. function PowerEase(power) {
  35021. if (power === void 0) { power = 2; }
  35022. var _this = _super.call(this) || this;
  35023. _this.power = power;
  35024. return _this;
  35025. }
  35026. PowerEase.prototype.easeInCore = function (gradient) {
  35027. var y = Math.max(0.0, this.power);
  35028. return Math.pow(gradient, y);
  35029. };
  35030. return PowerEase;
  35031. }(EasingFunction));
  35032. BABYLON.PowerEase = PowerEase;
  35033. var QuadraticEase = (function (_super) {
  35034. __extends(QuadraticEase, _super);
  35035. function QuadraticEase() {
  35036. return _super !== null && _super.apply(this, arguments) || this;
  35037. }
  35038. QuadraticEase.prototype.easeInCore = function (gradient) {
  35039. return (gradient * gradient);
  35040. };
  35041. return QuadraticEase;
  35042. }(EasingFunction));
  35043. BABYLON.QuadraticEase = QuadraticEase;
  35044. var QuarticEase = (function (_super) {
  35045. __extends(QuarticEase, _super);
  35046. function QuarticEase() {
  35047. return _super !== null && _super.apply(this, arguments) || this;
  35048. }
  35049. QuarticEase.prototype.easeInCore = function (gradient) {
  35050. return (gradient * gradient * gradient * gradient);
  35051. };
  35052. return QuarticEase;
  35053. }(EasingFunction));
  35054. BABYLON.QuarticEase = QuarticEase;
  35055. var QuinticEase = (function (_super) {
  35056. __extends(QuinticEase, _super);
  35057. function QuinticEase() {
  35058. return _super !== null && _super.apply(this, arguments) || this;
  35059. }
  35060. QuinticEase.prototype.easeInCore = function (gradient) {
  35061. return (gradient * gradient * gradient * gradient * gradient);
  35062. };
  35063. return QuinticEase;
  35064. }(EasingFunction));
  35065. BABYLON.QuinticEase = QuinticEase;
  35066. var SineEase = (function (_super) {
  35067. __extends(SineEase, _super);
  35068. function SineEase() {
  35069. return _super !== null && _super.apply(this, arguments) || this;
  35070. }
  35071. SineEase.prototype.easeInCore = function (gradient) {
  35072. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  35073. };
  35074. return SineEase;
  35075. }(EasingFunction));
  35076. BABYLON.SineEase = SineEase;
  35077. var BezierCurveEase = (function (_super) {
  35078. __extends(BezierCurveEase, _super);
  35079. function BezierCurveEase(x1, y1, x2, y2) {
  35080. if (x1 === void 0) { x1 = 0; }
  35081. if (y1 === void 0) { y1 = 0; }
  35082. if (x2 === void 0) { x2 = 1; }
  35083. if (y2 === void 0) { y2 = 1; }
  35084. var _this = _super.call(this) || this;
  35085. _this.x1 = x1;
  35086. _this.y1 = y1;
  35087. _this.x2 = x2;
  35088. _this.y2 = y2;
  35089. return _this;
  35090. }
  35091. BezierCurveEase.prototype.easeInCore = function (gradient) {
  35092. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  35093. };
  35094. return BezierCurveEase;
  35095. }(EasingFunction));
  35096. BABYLON.BezierCurveEase = BezierCurveEase;
  35097. })(BABYLON || (BABYLON = {}));
  35098. //# sourceMappingURL=babylon.easing.js.map
  35099. var BABYLON;
  35100. (function (BABYLON) {
  35101. var Condition = (function () {
  35102. function Condition(actionManager) {
  35103. this._actionManager = actionManager;
  35104. }
  35105. Condition.prototype.isValid = function () {
  35106. return true;
  35107. };
  35108. Condition.prototype._getProperty = function (propertyPath) {
  35109. return this._actionManager._getProperty(propertyPath);
  35110. };
  35111. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  35112. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35113. };
  35114. Condition.prototype.serialize = function () {
  35115. };
  35116. Condition.prototype._serialize = function (serializedCondition) {
  35117. return {
  35118. type: 2,
  35119. children: [],
  35120. name: serializedCondition.name,
  35121. properties: serializedCondition.properties
  35122. };
  35123. };
  35124. return Condition;
  35125. }());
  35126. BABYLON.Condition = Condition;
  35127. var ValueCondition = (function (_super) {
  35128. __extends(ValueCondition, _super);
  35129. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  35130. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  35131. var _this = _super.call(this, actionManager) || this;
  35132. _this.propertyPath = propertyPath;
  35133. _this.value = value;
  35134. _this.operator = operator;
  35135. _this._target = target;
  35136. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  35137. _this._property = _this._getProperty(_this.propertyPath);
  35138. return _this;
  35139. }
  35140. Object.defineProperty(ValueCondition, "IsEqual", {
  35141. get: function () {
  35142. return ValueCondition._IsEqual;
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(ValueCondition, "IsDifferent", {
  35148. get: function () {
  35149. return ValueCondition._IsDifferent;
  35150. },
  35151. enumerable: true,
  35152. configurable: true
  35153. });
  35154. Object.defineProperty(ValueCondition, "IsGreater", {
  35155. get: function () {
  35156. return ValueCondition._IsGreater;
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(ValueCondition, "IsLesser", {
  35162. get: function () {
  35163. return ValueCondition._IsLesser;
  35164. },
  35165. enumerable: true,
  35166. configurable: true
  35167. });
  35168. // Methods
  35169. ValueCondition.prototype.isValid = function () {
  35170. switch (this.operator) {
  35171. case ValueCondition.IsGreater:
  35172. return this._effectiveTarget[this._property] > this.value;
  35173. case ValueCondition.IsLesser:
  35174. return this._effectiveTarget[this._property] < this.value;
  35175. case ValueCondition.IsEqual:
  35176. case ValueCondition.IsDifferent:
  35177. var check;
  35178. if (this.value.equals) {
  35179. check = this.value.equals(this._effectiveTarget[this._property]);
  35180. }
  35181. else {
  35182. check = this.value === this._effectiveTarget[this._property];
  35183. }
  35184. return this.operator === ValueCondition.IsEqual ? check : !check;
  35185. }
  35186. return false;
  35187. };
  35188. ValueCondition.prototype.serialize = function () {
  35189. return this._serialize({
  35190. name: "ValueCondition",
  35191. properties: [
  35192. BABYLON.Action._GetTargetProperty(this._target),
  35193. { name: "propertyPath", value: this.propertyPath },
  35194. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35195. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35196. ]
  35197. });
  35198. };
  35199. ValueCondition.GetOperatorName = function (operator) {
  35200. switch (operator) {
  35201. case ValueCondition._IsEqual: return "IsEqual";
  35202. case ValueCondition._IsDifferent: return "IsDifferent";
  35203. case ValueCondition._IsGreater: return "IsGreater";
  35204. case ValueCondition._IsLesser: return "IsLesser";
  35205. default: return "";
  35206. }
  35207. };
  35208. return ValueCondition;
  35209. }(Condition));
  35210. // Statics
  35211. ValueCondition._IsEqual = 0;
  35212. ValueCondition._IsDifferent = 1;
  35213. ValueCondition._IsGreater = 2;
  35214. ValueCondition._IsLesser = 3;
  35215. BABYLON.ValueCondition = ValueCondition;
  35216. var PredicateCondition = (function (_super) {
  35217. __extends(PredicateCondition, _super);
  35218. function PredicateCondition(actionManager, predicate) {
  35219. var _this = _super.call(this, actionManager) || this;
  35220. _this.predicate = predicate;
  35221. return _this;
  35222. }
  35223. PredicateCondition.prototype.isValid = function () {
  35224. return this.predicate();
  35225. };
  35226. return PredicateCondition;
  35227. }(Condition));
  35228. BABYLON.PredicateCondition = PredicateCondition;
  35229. var StateCondition = (function (_super) {
  35230. __extends(StateCondition, _super);
  35231. function StateCondition(actionManager, target, value) {
  35232. var _this = _super.call(this, actionManager) || this;
  35233. _this.value = value;
  35234. _this._target = target;
  35235. return _this;
  35236. }
  35237. // Methods
  35238. StateCondition.prototype.isValid = function () {
  35239. return this._target.state === this.value;
  35240. };
  35241. StateCondition.prototype.serialize = function () {
  35242. return this._serialize({
  35243. name: "StateCondition",
  35244. properties: [
  35245. BABYLON.Action._GetTargetProperty(this._target),
  35246. { name: "value", value: this.value }
  35247. ]
  35248. });
  35249. };
  35250. return StateCondition;
  35251. }(Condition));
  35252. BABYLON.StateCondition = StateCondition;
  35253. })(BABYLON || (BABYLON = {}));
  35254. //# sourceMappingURL=babylon.condition.js.map
  35255. var BABYLON;
  35256. (function (BABYLON) {
  35257. var Action = (function () {
  35258. function Action(triggerOptions, condition) {
  35259. this.triggerOptions = triggerOptions;
  35260. if (triggerOptions.parameter) {
  35261. this.trigger = triggerOptions.trigger;
  35262. this._triggerParameter = triggerOptions.parameter;
  35263. }
  35264. else {
  35265. this.trigger = triggerOptions;
  35266. }
  35267. this._nextActiveAction = this;
  35268. this._condition = condition;
  35269. }
  35270. // Methods
  35271. Action.prototype._prepare = function () {
  35272. };
  35273. Action.prototype.getTriggerParameter = function () {
  35274. return this._triggerParameter;
  35275. };
  35276. Action.prototype._executeCurrent = function (evt) {
  35277. if (this._nextActiveAction._condition) {
  35278. var condition = this._nextActiveAction._condition;
  35279. var currentRenderId = this._actionManager.getScene().getRenderId();
  35280. // We cache the current evaluation for the current frame
  35281. if (condition._evaluationId === currentRenderId) {
  35282. if (!condition._currentResult) {
  35283. return;
  35284. }
  35285. }
  35286. else {
  35287. condition._evaluationId = currentRenderId;
  35288. if (!condition.isValid()) {
  35289. condition._currentResult = false;
  35290. return;
  35291. }
  35292. condition._currentResult = true;
  35293. }
  35294. }
  35295. this._nextActiveAction.execute(evt);
  35296. this.skipToNextActiveAction();
  35297. };
  35298. Action.prototype.execute = function (evt) {
  35299. };
  35300. Action.prototype.skipToNextActiveAction = function () {
  35301. if (this._nextActiveAction._child) {
  35302. if (!this._nextActiveAction._child._actionManager) {
  35303. this._nextActiveAction._child._actionManager = this._actionManager;
  35304. }
  35305. this._nextActiveAction = this._nextActiveAction._child;
  35306. }
  35307. else {
  35308. this._nextActiveAction = this;
  35309. }
  35310. };
  35311. Action.prototype.then = function (action) {
  35312. this._child = action;
  35313. action._actionManager = this._actionManager;
  35314. action._prepare();
  35315. return action;
  35316. };
  35317. Action.prototype._getProperty = function (propertyPath) {
  35318. return this._actionManager._getProperty(propertyPath);
  35319. };
  35320. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35321. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35322. };
  35323. Action.prototype.serialize = function (parent) {
  35324. };
  35325. // Called by BABYLON.Action objects in serialize(...). Internal use
  35326. Action.prototype._serialize = function (serializedAction, parent) {
  35327. var serializationObject = {
  35328. type: 1,
  35329. children: [],
  35330. name: serializedAction.name,
  35331. properties: serializedAction.properties || []
  35332. };
  35333. // Serialize child
  35334. if (this._child) {
  35335. this._child.serialize(serializationObject);
  35336. }
  35337. // Check if "this" has a condition
  35338. if (this._condition) {
  35339. var serializedCondition = this._condition.serialize();
  35340. serializedCondition.children.push(serializationObject);
  35341. if (parent) {
  35342. parent.children.push(serializedCondition);
  35343. }
  35344. return serializedCondition;
  35345. }
  35346. if (parent) {
  35347. parent.children.push(serializationObject);
  35348. }
  35349. return serializationObject;
  35350. };
  35351. return Action;
  35352. }());
  35353. Action._SerializeValueAsString = function (value) {
  35354. if (typeof value === "number") {
  35355. return value.toString();
  35356. }
  35357. if (typeof value === "boolean") {
  35358. return value ? "true" : "false";
  35359. }
  35360. if (value instanceof BABYLON.Vector2) {
  35361. return value.x + ", " + value.y;
  35362. }
  35363. if (value instanceof BABYLON.Vector3) {
  35364. return value.x + ", " + value.y + ", " + value.z;
  35365. }
  35366. if (value instanceof BABYLON.Color3) {
  35367. return value.r + ", " + value.g + ", " + value.b;
  35368. }
  35369. if (value instanceof BABYLON.Color4) {
  35370. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35371. }
  35372. return value; // string
  35373. };
  35374. Action._GetTargetProperty = function (target) {
  35375. return {
  35376. name: "target",
  35377. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35378. : target instanceof BABYLON.Light ? "LightProperties"
  35379. : target instanceof BABYLON.Camera ? "CameraProperties"
  35380. : "SceneProperties",
  35381. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35382. };
  35383. };
  35384. BABYLON.Action = Action;
  35385. })(BABYLON || (BABYLON = {}));
  35386. //# sourceMappingURL=babylon.action.js.map
  35387. var BABYLON;
  35388. (function (BABYLON) {
  35389. /**
  35390. * ActionEvent is the event beint sent when an action is triggered.
  35391. */
  35392. var ActionEvent = (function () {
  35393. /**
  35394. * @constructor
  35395. * @param source The mesh or sprite that triggered the action.
  35396. * @param pointerX The X mouse cursor position at the time of the event
  35397. * @param pointerY The Y mouse cursor position at the time of the event
  35398. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35399. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35400. */
  35401. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35402. this.source = source;
  35403. this.pointerX = pointerX;
  35404. this.pointerY = pointerY;
  35405. this.meshUnderPointer = meshUnderPointer;
  35406. this.sourceEvent = sourceEvent;
  35407. this.additionalData = additionalData;
  35408. }
  35409. /**
  35410. * Helper function to auto-create an ActionEvent from a source mesh.
  35411. * @param source The source mesh that triggered the event
  35412. * @param evt {Event} The original (browser) event
  35413. */
  35414. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35415. var scene = source.getScene();
  35416. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35417. };
  35418. /**
  35419. * Helper function to auto-create an ActionEvent from a source mesh.
  35420. * @param source The source sprite that triggered the event
  35421. * @param scene Scene associated with the sprite
  35422. * @param evt {Event} The original (browser) event
  35423. */
  35424. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35425. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35426. };
  35427. /**
  35428. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35429. * @param scene the scene where the event occurred
  35430. * @param evt {Event} The original (browser) event
  35431. */
  35432. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35433. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35434. };
  35435. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35436. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35437. };
  35438. return ActionEvent;
  35439. }());
  35440. BABYLON.ActionEvent = ActionEvent;
  35441. /**
  35442. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35443. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35444. */
  35445. var ActionManager = (function () {
  35446. function ActionManager(scene) {
  35447. // Members
  35448. this.actions = new Array();
  35449. this.hoverCursor = '';
  35450. this._scene = scene;
  35451. scene._actionManagers.push(this);
  35452. }
  35453. Object.defineProperty(ActionManager, "NothingTrigger", {
  35454. get: function () {
  35455. return ActionManager._NothingTrigger;
  35456. },
  35457. enumerable: true,
  35458. configurable: true
  35459. });
  35460. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35461. get: function () {
  35462. return ActionManager._OnPickTrigger;
  35463. },
  35464. enumerable: true,
  35465. configurable: true
  35466. });
  35467. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35468. get: function () {
  35469. return ActionManager._OnLeftPickTrigger;
  35470. },
  35471. enumerable: true,
  35472. configurable: true
  35473. });
  35474. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35475. get: function () {
  35476. return ActionManager._OnRightPickTrigger;
  35477. },
  35478. enumerable: true,
  35479. configurable: true
  35480. });
  35481. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35482. get: function () {
  35483. return ActionManager._OnCenterPickTrigger;
  35484. },
  35485. enumerable: true,
  35486. configurable: true
  35487. });
  35488. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35489. get: function () {
  35490. return ActionManager._OnPickDownTrigger;
  35491. },
  35492. enumerable: true,
  35493. configurable: true
  35494. });
  35495. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  35496. get: function () {
  35497. return ActionManager._OnDoublePickTrigger;
  35498. },
  35499. enumerable: true,
  35500. configurable: true
  35501. });
  35502. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35503. get: function () {
  35504. return ActionManager._OnPickUpTrigger;
  35505. },
  35506. enumerable: true,
  35507. configurable: true
  35508. });
  35509. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35510. /// This trigger will only be raised if you also declared a OnPickDown
  35511. get: function () {
  35512. return ActionManager._OnPickOutTrigger;
  35513. },
  35514. enumerable: true,
  35515. configurable: true
  35516. });
  35517. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35518. get: function () {
  35519. return ActionManager._OnLongPressTrigger;
  35520. },
  35521. enumerable: true,
  35522. configurable: true
  35523. });
  35524. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35525. get: function () {
  35526. return ActionManager._OnPointerOverTrigger;
  35527. },
  35528. enumerable: true,
  35529. configurable: true
  35530. });
  35531. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35532. get: function () {
  35533. return ActionManager._OnPointerOutTrigger;
  35534. },
  35535. enumerable: true,
  35536. configurable: true
  35537. });
  35538. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35539. get: function () {
  35540. return ActionManager._OnEveryFrameTrigger;
  35541. },
  35542. enumerable: true,
  35543. configurable: true
  35544. });
  35545. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35546. get: function () {
  35547. return ActionManager._OnIntersectionEnterTrigger;
  35548. },
  35549. enumerable: true,
  35550. configurable: true
  35551. });
  35552. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35553. get: function () {
  35554. return ActionManager._OnIntersectionExitTrigger;
  35555. },
  35556. enumerable: true,
  35557. configurable: true
  35558. });
  35559. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35560. get: function () {
  35561. return ActionManager._OnKeyDownTrigger;
  35562. },
  35563. enumerable: true,
  35564. configurable: true
  35565. });
  35566. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35567. get: function () {
  35568. return ActionManager._OnKeyUpTrigger;
  35569. },
  35570. enumerable: true,
  35571. configurable: true
  35572. });
  35573. // Methods
  35574. ActionManager.prototype.dispose = function () {
  35575. var index = this._scene._actionManagers.indexOf(this);
  35576. for (var i = 0; i < this.actions.length; i++) {
  35577. var action = this.actions[i];
  35578. ActionManager.Triggers[action.trigger]--;
  35579. if (ActionManager.Triggers[action.trigger] === 0) {
  35580. delete ActionManager.Triggers[action.trigger];
  35581. }
  35582. }
  35583. if (index > -1) {
  35584. this._scene._actionManagers.splice(index, 1);
  35585. }
  35586. };
  35587. ActionManager.prototype.getScene = function () {
  35588. return this._scene;
  35589. };
  35590. /**
  35591. * Does this action manager handles actions of any of the given triggers
  35592. * @param {number[]} triggers - the triggers to be tested
  35593. * @return {boolean} whether one (or more) of the triggers is handeled
  35594. */
  35595. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35596. for (var index = 0; index < this.actions.length; index++) {
  35597. var action = this.actions[index];
  35598. if (triggers.indexOf(action.trigger) > -1) {
  35599. return true;
  35600. }
  35601. }
  35602. return false;
  35603. };
  35604. /**
  35605. * Does this action manager handles actions of a given trigger
  35606. * @param {number} trigger - the trigger to be tested
  35607. * @return {boolean} whether the trigger is handeled
  35608. */
  35609. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35610. for (var index = 0; index < this.actions.length; index++) {
  35611. var action = this.actions[index];
  35612. if (action.trigger === trigger) {
  35613. return true;
  35614. }
  35615. }
  35616. return false;
  35617. };
  35618. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35619. /**
  35620. * Does this action manager has pointer triggers
  35621. * @return {boolean} whether or not it has pointer triggers
  35622. */
  35623. get: function () {
  35624. for (var index = 0; index < this.actions.length; index++) {
  35625. var action = this.actions[index];
  35626. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35627. return true;
  35628. }
  35629. }
  35630. return false;
  35631. },
  35632. enumerable: true,
  35633. configurable: true
  35634. });
  35635. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35636. /**
  35637. * Does this action manager has pick triggers
  35638. * @return {boolean} whether or not it has pick triggers
  35639. */
  35640. get: function () {
  35641. for (var index = 0; index < this.actions.length; index++) {
  35642. var action = this.actions[index];
  35643. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35644. return true;
  35645. }
  35646. }
  35647. return false;
  35648. },
  35649. enumerable: true,
  35650. configurable: true
  35651. });
  35652. Object.defineProperty(ActionManager, "HasTriggers", {
  35653. /**
  35654. * Does exist one action manager with at least one trigger
  35655. * @return {boolean} whether or not it exists one action manager with one trigger
  35656. **/
  35657. get: function () {
  35658. for (var t in ActionManager.Triggers) {
  35659. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35660. return true;
  35661. }
  35662. }
  35663. return false;
  35664. },
  35665. enumerable: true,
  35666. configurable: true
  35667. });
  35668. Object.defineProperty(ActionManager, "HasPickTriggers", {
  35669. /**
  35670. * Does exist one action manager with at least one pick trigger
  35671. * @return {boolean} whether or not it exists one action manager with one pick trigger
  35672. **/
  35673. get: function () {
  35674. for (var t in ActionManager.Triggers) {
  35675. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35676. var t_int = parseInt(t);
  35677. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  35678. return true;
  35679. }
  35680. }
  35681. }
  35682. return false;
  35683. },
  35684. enumerable: true,
  35685. configurable: true
  35686. });
  35687. /**
  35688. * Does exist one action manager that handles actions of a given trigger
  35689. * @param {number} trigger - the trigger to be tested
  35690. * @return {boolean} whether the trigger is handeled by at least one action manager
  35691. **/
  35692. ActionManager.HasSpecificTrigger = function (trigger) {
  35693. for (var t in ActionManager.Triggers) {
  35694. if (ActionManager.Triggers.hasOwnProperty(t)) {
  35695. var t_int = parseInt(t);
  35696. if (t_int === trigger) {
  35697. return true;
  35698. }
  35699. }
  35700. }
  35701. return false;
  35702. };
  35703. /**
  35704. * Registers an action to this action manager
  35705. * @param {BABYLON.Action} action - the action to be registered
  35706. * @return {BABYLON.Action} the action amended (prepared) after registration
  35707. */
  35708. ActionManager.prototype.registerAction = function (action) {
  35709. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35710. if (this.getScene().actionManager !== this) {
  35711. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35712. return null;
  35713. }
  35714. }
  35715. this.actions.push(action);
  35716. if (ActionManager.Triggers[action.trigger]) {
  35717. ActionManager.Triggers[action.trigger]++;
  35718. }
  35719. else {
  35720. ActionManager.Triggers[action.trigger] = 1;
  35721. }
  35722. action._actionManager = this;
  35723. action._prepare();
  35724. return action;
  35725. };
  35726. /**
  35727. * Process a specific trigger
  35728. * @param {number} trigger - the trigger to process
  35729. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35730. */
  35731. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35732. for (var index = 0; index < this.actions.length; index++) {
  35733. var action = this.actions[index];
  35734. if (action.trigger === trigger) {
  35735. if (trigger === ActionManager.OnKeyUpTrigger
  35736. || trigger === ActionManager.OnKeyDownTrigger) {
  35737. var parameter = action.getTriggerParameter();
  35738. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  35739. if (!parameter.toLowerCase) {
  35740. continue;
  35741. }
  35742. var lowerCase = parameter.toLowerCase();
  35743. if (lowerCase !== evt.sourceEvent.key) {
  35744. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35745. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35746. if (actualkey !== lowerCase) {
  35747. continue;
  35748. }
  35749. }
  35750. }
  35751. }
  35752. action._executeCurrent(evt);
  35753. }
  35754. }
  35755. };
  35756. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35757. var properties = propertyPath.split(".");
  35758. for (var index = 0; index < properties.length - 1; index++) {
  35759. target = target[properties[index]];
  35760. }
  35761. return target;
  35762. };
  35763. ActionManager.prototype._getProperty = function (propertyPath) {
  35764. var properties = propertyPath.split(".");
  35765. return properties[properties.length - 1];
  35766. };
  35767. ActionManager.prototype.serialize = function (name) {
  35768. var root = {
  35769. children: [],
  35770. name: name,
  35771. type: 3,
  35772. properties: [] // Empty for root but required
  35773. };
  35774. for (var i = 0; i < this.actions.length; i++) {
  35775. var triggerObject = {
  35776. type: 0,
  35777. children: [],
  35778. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35779. properties: []
  35780. };
  35781. var triggerOptions = this.actions[i].triggerOptions;
  35782. if (triggerOptions && typeof triggerOptions !== "number") {
  35783. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35784. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35785. }
  35786. else {
  35787. var parameter = {};
  35788. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35789. if (triggerOptions.parameter.mesh) {
  35790. parameter._meshId = triggerOptions.parameter.mesh.id;
  35791. }
  35792. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35793. }
  35794. }
  35795. // Serialize child action, recursively
  35796. this.actions[i].serialize(triggerObject);
  35797. // Add serialized trigger
  35798. root.children.push(triggerObject);
  35799. }
  35800. return root;
  35801. };
  35802. ActionManager.Parse = function (parsedActions, object, scene) {
  35803. var actionManager = new BABYLON.ActionManager(scene);
  35804. if (object === null)
  35805. scene.actionManager = actionManager;
  35806. else
  35807. object.actionManager = actionManager;
  35808. // instanciate a new object
  35809. var instanciate = function (name, params) {
  35810. var newInstance = Object.create(BABYLON[name].prototype);
  35811. newInstance.constructor.apply(newInstance, params);
  35812. return newInstance;
  35813. };
  35814. var parseParameter = function (name, value, target, propertyPath) {
  35815. if (propertyPath === null) {
  35816. // String, boolean or float
  35817. var floatValue = parseFloat(value);
  35818. if (value === "true" || value === "false")
  35819. return value === "true";
  35820. else
  35821. return isNaN(floatValue) ? value : floatValue;
  35822. }
  35823. var effectiveTarget = propertyPath.split(".");
  35824. var values = value.split(",");
  35825. // Get effective Target
  35826. for (var i = 0; i < effectiveTarget.length; i++) {
  35827. target = target[effectiveTarget[i]];
  35828. }
  35829. // Return appropriate value with its type
  35830. if (typeof (target) === "boolean")
  35831. return values[0] === "true";
  35832. if (typeof (target) === "string")
  35833. return values[0];
  35834. // Parameters with multiple values such as Vector3 etc.
  35835. var split = new Array();
  35836. for (var i = 0; i < values.length; i++)
  35837. split.push(parseFloat(values[i]));
  35838. if (target instanceof BABYLON.Vector3)
  35839. return BABYLON.Vector3.FromArray(split);
  35840. if (target instanceof BABYLON.Vector4)
  35841. return BABYLON.Vector4.FromArray(split);
  35842. if (target instanceof BABYLON.Color3)
  35843. return BABYLON.Color3.FromArray(split);
  35844. if (target instanceof BABYLON.Color4)
  35845. return BABYLON.Color4.FromArray(split);
  35846. return parseFloat(values[0]);
  35847. };
  35848. // traverse graph per trigger
  35849. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35850. if (combineArray === void 0) { combineArray = null; }
  35851. if (parsedAction.detached)
  35852. return;
  35853. var parameters = new Array();
  35854. var target = null;
  35855. var propertyPath = null;
  35856. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35857. // Parameters
  35858. if (parsedAction.type === 2)
  35859. parameters.push(actionManager);
  35860. else
  35861. parameters.push(trigger);
  35862. if (combine) {
  35863. var actions = new Array();
  35864. for (var j = 0; j < parsedAction.combine.length; j++) {
  35865. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35866. }
  35867. parameters.push(actions);
  35868. }
  35869. else {
  35870. for (var i = 0; i < parsedAction.properties.length; i++) {
  35871. var value = parsedAction.properties[i].value;
  35872. var name = parsedAction.properties[i].name;
  35873. var targetType = parsedAction.properties[i].targetType;
  35874. if (name === "target")
  35875. if (targetType !== null && targetType === "SceneProperties")
  35876. value = target = scene;
  35877. else
  35878. value = target = scene.getNodeByName(value);
  35879. else if (name === "parent")
  35880. value = scene.getNodeByName(value);
  35881. else if (name === "sound")
  35882. value = scene.getSoundByName(value);
  35883. else if (name !== "propertyPath") {
  35884. if (parsedAction.type === 2 && name === "operator")
  35885. value = BABYLON.ValueCondition[value];
  35886. else
  35887. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35888. }
  35889. else {
  35890. propertyPath = value;
  35891. }
  35892. parameters.push(value);
  35893. }
  35894. }
  35895. if (combineArray === null) {
  35896. parameters.push(condition);
  35897. }
  35898. else {
  35899. parameters.push(null);
  35900. }
  35901. // If interpolate value action
  35902. if (parsedAction.name === "InterpolateValueAction") {
  35903. var param = parameters[parameters.length - 2];
  35904. parameters[parameters.length - 1] = param;
  35905. parameters[parameters.length - 2] = condition;
  35906. }
  35907. // Action or condition(s) and not CombineAction
  35908. var newAction = instanciate(parsedAction.name, parameters);
  35909. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35910. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35911. if (action)
  35912. action.then(nothing);
  35913. else
  35914. actionManager.registerAction(nothing);
  35915. action = nothing;
  35916. }
  35917. if (combineArray === null) {
  35918. if (newAction instanceof BABYLON.Condition) {
  35919. condition = newAction;
  35920. newAction = action;
  35921. }
  35922. else {
  35923. condition = null;
  35924. if (action)
  35925. action.then(newAction);
  35926. else
  35927. actionManager.registerAction(newAction);
  35928. }
  35929. }
  35930. else {
  35931. combineArray.push(newAction);
  35932. }
  35933. for (var i = 0; i < parsedAction.children.length; i++)
  35934. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35935. };
  35936. // triggers
  35937. for (var i = 0; i < parsedActions.children.length; i++) {
  35938. var triggerParams;
  35939. var trigger = parsedActions.children[i];
  35940. if (trigger.properties.length > 0) {
  35941. var param = trigger.properties[0].value;
  35942. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35943. if (value._meshId) {
  35944. value.mesh = scene.getMeshByID(value._meshId);
  35945. }
  35946. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35947. }
  35948. else
  35949. triggerParams = BABYLON.ActionManager[trigger.name];
  35950. for (var j = 0; j < trigger.children.length; j++) {
  35951. if (!trigger.detached)
  35952. traverse(trigger.children[j], triggerParams, null, null);
  35953. }
  35954. }
  35955. };
  35956. ActionManager.GetTriggerName = function (trigger) {
  35957. switch (trigger) {
  35958. case 0: return "NothingTrigger";
  35959. case 1: return "OnPickTrigger";
  35960. case 2: return "OnLeftPickTrigger";
  35961. case 3: return "OnRightPickTrigger";
  35962. case 4: return "OnCenterPickTrigger";
  35963. case 5: return "OnPickDownTrigger";
  35964. case 6: return "OnPickUpTrigger";
  35965. case 7: return "OnLongPressTrigger";
  35966. case 8: return "OnPointerOverTrigger";
  35967. case 9: return "OnPointerOutTrigger";
  35968. case 10: return "OnEveryFrameTrigger";
  35969. case 11: return "OnIntersectionEnterTrigger";
  35970. case 12: return "OnIntersectionExitTrigger";
  35971. case 13: return "OnKeyDownTrigger";
  35972. case 14: return "OnKeyUpTrigger";
  35973. case 15: return "OnPickOutTrigger";
  35974. default: return "";
  35975. }
  35976. };
  35977. return ActionManager;
  35978. }());
  35979. // Statics
  35980. ActionManager._NothingTrigger = 0;
  35981. ActionManager._OnPickTrigger = 1;
  35982. ActionManager._OnLeftPickTrigger = 2;
  35983. ActionManager._OnRightPickTrigger = 3;
  35984. ActionManager._OnCenterPickTrigger = 4;
  35985. ActionManager._OnPickDownTrigger = 5;
  35986. ActionManager._OnDoublePickTrigger = 6;
  35987. ActionManager._OnPickUpTrigger = 7;
  35988. ActionManager._OnLongPressTrigger = 8;
  35989. ActionManager._OnPointerOverTrigger = 9;
  35990. ActionManager._OnPointerOutTrigger = 10;
  35991. ActionManager._OnEveryFrameTrigger = 11;
  35992. ActionManager._OnIntersectionEnterTrigger = 12;
  35993. ActionManager._OnIntersectionExitTrigger = 13;
  35994. ActionManager._OnKeyDownTrigger = 14;
  35995. ActionManager._OnKeyUpTrigger = 15;
  35996. ActionManager._OnPickOutTrigger = 16;
  35997. ActionManager.Triggers = {};
  35998. BABYLON.ActionManager = ActionManager;
  35999. })(BABYLON || (BABYLON = {}));
  36000. //# sourceMappingURL=babylon.actionManager.js.map
  36001. var BABYLON;
  36002. (function (BABYLON) {
  36003. var InterpolateValueAction = (function (_super) {
  36004. __extends(InterpolateValueAction, _super);
  36005. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36006. if (duration === void 0) { duration = 1000; }
  36007. var _this = _super.call(this, triggerOptions, condition) || this;
  36008. _this.propertyPath = propertyPath;
  36009. _this.value = value;
  36010. _this.duration = duration;
  36011. _this.stopOtherAnimations = stopOtherAnimations;
  36012. _this.onInterpolationDone = onInterpolationDone;
  36013. _this._target = _this._effectiveTarget = target;
  36014. return _this;
  36015. }
  36016. InterpolateValueAction.prototype._prepare = function () {
  36017. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36018. this._property = this._getProperty(this.propertyPath);
  36019. };
  36020. InterpolateValueAction.prototype.execute = function () {
  36021. var scene = this._actionManager.getScene();
  36022. var keys = [
  36023. {
  36024. frame: 0,
  36025. value: this._effectiveTarget[this._property]
  36026. }, {
  36027. frame: 100,
  36028. value: this.value
  36029. }
  36030. ];
  36031. var dataType;
  36032. if (typeof this.value === "number") {
  36033. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36034. }
  36035. else if (this.value instanceof BABYLON.Color3) {
  36036. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36037. }
  36038. else if (this.value instanceof BABYLON.Vector3) {
  36039. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36040. }
  36041. else if (this.value instanceof BABYLON.Matrix) {
  36042. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36043. }
  36044. else if (this.value instanceof BABYLON.Quaternion) {
  36045. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36046. }
  36047. else {
  36048. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36049. return;
  36050. }
  36051. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36052. animation.setKeys(keys);
  36053. if (this.stopOtherAnimations) {
  36054. scene.stopAnimation(this._effectiveTarget);
  36055. }
  36056. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36057. };
  36058. InterpolateValueAction.prototype.serialize = function (parent) {
  36059. return _super.prototype._serialize.call(this, {
  36060. name: "InterpolateValueAction",
  36061. properties: [
  36062. BABYLON.Action._GetTargetProperty(this._target),
  36063. { name: "propertyPath", value: this.propertyPath },
  36064. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36065. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36066. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36067. ]
  36068. }, parent);
  36069. };
  36070. return InterpolateValueAction;
  36071. }(BABYLON.Action));
  36072. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36073. })(BABYLON || (BABYLON = {}));
  36074. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36075. var BABYLON;
  36076. (function (BABYLON) {
  36077. var SwitchBooleanAction = (function (_super) {
  36078. __extends(SwitchBooleanAction, _super);
  36079. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36080. var _this = _super.call(this, triggerOptions, condition) || this;
  36081. _this.propertyPath = propertyPath;
  36082. _this._target = _this._effectiveTarget = target;
  36083. return _this;
  36084. }
  36085. SwitchBooleanAction.prototype._prepare = function () {
  36086. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36087. this._property = this._getProperty(this.propertyPath);
  36088. };
  36089. SwitchBooleanAction.prototype.execute = function () {
  36090. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36091. };
  36092. SwitchBooleanAction.prototype.serialize = function (parent) {
  36093. return _super.prototype._serialize.call(this, {
  36094. name: "SwitchBooleanAction",
  36095. properties: [
  36096. BABYLON.Action._GetTargetProperty(this._target),
  36097. { name: "propertyPath", value: this.propertyPath }
  36098. ]
  36099. }, parent);
  36100. };
  36101. return SwitchBooleanAction;
  36102. }(BABYLON.Action));
  36103. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36104. var SetStateAction = (function (_super) {
  36105. __extends(SetStateAction, _super);
  36106. function SetStateAction(triggerOptions, target, value, condition) {
  36107. var _this = _super.call(this, triggerOptions, condition) || this;
  36108. _this.value = value;
  36109. _this._target = target;
  36110. return _this;
  36111. }
  36112. SetStateAction.prototype.execute = function () {
  36113. this._target.state = this.value;
  36114. };
  36115. SetStateAction.prototype.serialize = function (parent) {
  36116. return _super.prototype._serialize.call(this, {
  36117. name: "SetStateAction",
  36118. properties: [
  36119. BABYLON.Action._GetTargetProperty(this._target),
  36120. { name: "value", value: this.value }
  36121. ]
  36122. }, parent);
  36123. };
  36124. return SetStateAction;
  36125. }(BABYLON.Action));
  36126. BABYLON.SetStateAction = SetStateAction;
  36127. var SetValueAction = (function (_super) {
  36128. __extends(SetValueAction, _super);
  36129. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36130. var _this = _super.call(this, triggerOptions, condition) || this;
  36131. _this.propertyPath = propertyPath;
  36132. _this.value = value;
  36133. _this._target = _this._effectiveTarget = target;
  36134. return _this;
  36135. }
  36136. SetValueAction.prototype._prepare = function () {
  36137. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36138. this._property = this._getProperty(this.propertyPath);
  36139. };
  36140. SetValueAction.prototype.execute = function () {
  36141. this._effectiveTarget[this._property] = this.value;
  36142. if (this._target.markAsDirty) {
  36143. this._target.markAsDirty(this._property);
  36144. }
  36145. };
  36146. SetValueAction.prototype.serialize = function (parent) {
  36147. return _super.prototype._serialize.call(this, {
  36148. name: "SetValueAction",
  36149. properties: [
  36150. BABYLON.Action._GetTargetProperty(this._target),
  36151. { name: "propertyPath", value: this.propertyPath },
  36152. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36153. ]
  36154. }, parent);
  36155. };
  36156. return SetValueAction;
  36157. }(BABYLON.Action));
  36158. BABYLON.SetValueAction = SetValueAction;
  36159. var IncrementValueAction = (function (_super) {
  36160. __extends(IncrementValueAction, _super);
  36161. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  36162. var _this = _super.call(this, triggerOptions, condition) || this;
  36163. _this.propertyPath = propertyPath;
  36164. _this.value = value;
  36165. _this._target = _this._effectiveTarget = target;
  36166. return _this;
  36167. }
  36168. IncrementValueAction.prototype._prepare = function () {
  36169. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36170. this._property = this._getProperty(this.propertyPath);
  36171. if (typeof this._effectiveTarget[this._property] !== "number") {
  36172. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  36173. }
  36174. };
  36175. IncrementValueAction.prototype.execute = function () {
  36176. this._effectiveTarget[this._property] += this.value;
  36177. if (this._target.markAsDirty) {
  36178. this._target.markAsDirty(this._property);
  36179. }
  36180. };
  36181. IncrementValueAction.prototype.serialize = function (parent) {
  36182. return _super.prototype._serialize.call(this, {
  36183. name: "IncrementValueAction",
  36184. properties: [
  36185. BABYLON.Action._GetTargetProperty(this._target),
  36186. { name: "propertyPath", value: this.propertyPath },
  36187. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  36188. ]
  36189. }, parent);
  36190. };
  36191. return IncrementValueAction;
  36192. }(BABYLON.Action));
  36193. BABYLON.IncrementValueAction = IncrementValueAction;
  36194. var PlayAnimationAction = (function (_super) {
  36195. __extends(PlayAnimationAction, _super);
  36196. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  36197. var _this = _super.call(this, triggerOptions, condition) || this;
  36198. _this.from = from;
  36199. _this.to = to;
  36200. _this.loop = loop;
  36201. _this._target = target;
  36202. return _this;
  36203. }
  36204. PlayAnimationAction.prototype._prepare = function () {
  36205. };
  36206. PlayAnimationAction.prototype.execute = function () {
  36207. var scene = this._actionManager.getScene();
  36208. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  36209. };
  36210. PlayAnimationAction.prototype.serialize = function (parent) {
  36211. return _super.prototype._serialize.call(this, {
  36212. name: "PlayAnimationAction",
  36213. properties: [
  36214. BABYLON.Action._GetTargetProperty(this._target),
  36215. { name: "from", value: String(this.from) },
  36216. { name: "to", value: String(this.to) },
  36217. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  36218. ]
  36219. }, parent);
  36220. };
  36221. return PlayAnimationAction;
  36222. }(BABYLON.Action));
  36223. BABYLON.PlayAnimationAction = PlayAnimationAction;
  36224. var StopAnimationAction = (function (_super) {
  36225. __extends(StopAnimationAction, _super);
  36226. function StopAnimationAction(triggerOptions, target, condition) {
  36227. var _this = _super.call(this, triggerOptions, condition) || this;
  36228. _this._target = target;
  36229. return _this;
  36230. }
  36231. StopAnimationAction.prototype._prepare = function () {
  36232. };
  36233. StopAnimationAction.prototype.execute = function () {
  36234. var scene = this._actionManager.getScene();
  36235. scene.stopAnimation(this._target);
  36236. };
  36237. StopAnimationAction.prototype.serialize = function (parent) {
  36238. return _super.prototype._serialize.call(this, {
  36239. name: "StopAnimationAction",
  36240. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36241. }, parent);
  36242. };
  36243. return StopAnimationAction;
  36244. }(BABYLON.Action));
  36245. BABYLON.StopAnimationAction = StopAnimationAction;
  36246. var DoNothingAction = (function (_super) {
  36247. __extends(DoNothingAction, _super);
  36248. function DoNothingAction(triggerOptions, condition) {
  36249. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36250. return _super.call(this, triggerOptions, condition) || this;
  36251. }
  36252. DoNothingAction.prototype.execute = function () {
  36253. };
  36254. DoNothingAction.prototype.serialize = function (parent) {
  36255. return _super.prototype._serialize.call(this, {
  36256. name: "DoNothingAction",
  36257. properties: []
  36258. }, parent);
  36259. };
  36260. return DoNothingAction;
  36261. }(BABYLON.Action));
  36262. BABYLON.DoNothingAction = DoNothingAction;
  36263. var CombineAction = (function (_super) {
  36264. __extends(CombineAction, _super);
  36265. function CombineAction(triggerOptions, children, condition) {
  36266. var _this = _super.call(this, triggerOptions, condition) || this;
  36267. _this.children = children;
  36268. return _this;
  36269. }
  36270. CombineAction.prototype._prepare = function () {
  36271. for (var index = 0; index < this.children.length; index++) {
  36272. this.children[index]._actionManager = this._actionManager;
  36273. this.children[index]._prepare();
  36274. }
  36275. };
  36276. CombineAction.prototype.execute = function (evt) {
  36277. for (var index = 0; index < this.children.length; index++) {
  36278. this.children[index].execute(evt);
  36279. }
  36280. };
  36281. CombineAction.prototype.serialize = function (parent) {
  36282. var serializationObject = _super.prototype._serialize.call(this, {
  36283. name: "CombineAction",
  36284. properties: [],
  36285. combine: []
  36286. }, parent);
  36287. for (var i = 0; i < this.children.length; i++) {
  36288. serializationObject.combine.push(this.children[i].serialize(null));
  36289. }
  36290. return serializationObject;
  36291. };
  36292. return CombineAction;
  36293. }(BABYLON.Action));
  36294. BABYLON.CombineAction = CombineAction;
  36295. var ExecuteCodeAction = (function (_super) {
  36296. __extends(ExecuteCodeAction, _super);
  36297. function ExecuteCodeAction(triggerOptions, func, condition) {
  36298. var _this = _super.call(this, triggerOptions, condition) || this;
  36299. _this.func = func;
  36300. return _this;
  36301. }
  36302. ExecuteCodeAction.prototype.execute = function (evt) {
  36303. this.func(evt);
  36304. };
  36305. return ExecuteCodeAction;
  36306. }(BABYLON.Action));
  36307. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36308. var SetParentAction = (function (_super) {
  36309. __extends(SetParentAction, _super);
  36310. function SetParentAction(triggerOptions, target, parent, condition) {
  36311. var _this = _super.call(this, triggerOptions, condition) || this;
  36312. _this._target = target;
  36313. _this._parent = parent;
  36314. return _this;
  36315. }
  36316. SetParentAction.prototype._prepare = function () {
  36317. };
  36318. SetParentAction.prototype.execute = function () {
  36319. if (this._target.parent === this._parent) {
  36320. return;
  36321. }
  36322. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36323. invertParentWorldMatrix.invert();
  36324. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36325. this._target.parent = this._parent;
  36326. };
  36327. SetParentAction.prototype.serialize = function (parent) {
  36328. return _super.prototype._serialize.call(this, {
  36329. name: "SetParentAction",
  36330. properties: [
  36331. BABYLON.Action._GetTargetProperty(this._target),
  36332. BABYLON.Action._GetTargetProperty(this._parent),
  36333. ]
  36334. }, parent);
  36335. };
  36336. return SetParentAction;
  36337. }(BABYLON.Action));
  36338. BABYLON.SetParentAction = SetParentAction;
  36339. var PlaySoundAction = (function (_super) {
  36340. __extends(PlaySoundAction, _super);
  36341. function PlaySoundAction(triggerOptions, sound, condition) {
  36342. var _this = _super.call(this, triggerOptions, condition) || this;
  36343. _this._sound = sound;
  36344. return _this;
  36345. }
  36346. PlaySoundAction.prototype._prepare = function () {
  36347. };
  36348. PlaySoundAction.prototype.execute = function () {
  36349. if (this._sound !== undefined)
  36350. this._sound.play();
  36351. };
  36352. PlaySoundAction.prototype.serialize = function (parent) {
  36353. return _super.prototype._serialize.call(this, {
  36354. name: "PlaySoundAction",
  36355. properties: [{ name: "sound", value: this._sound.name }]
  36356. }, parent);
  36357. };
  36358. return PlaySoundAction;
  36359. }(BABYLON.Action));
  36360. BABYLON.PlaySoundAction = PlaySoundAction;
  36361. var StopSoundAction = (function (_super) {
  36362. __extends(StopSoundAction, _super);
  36363. function StopSoundAction(triggerOptions, sound, condition) {
  36364. var _this = _super.call(this, triggerOptions, condition) || this;
  36365. _this._sound = sound;
  36366. return _this;
  36367. }
  36368. StopSoundAction.prototype._prepare = function () {
  36369. };
  36370. StopSoundAction.prototype.execute = function () {
  36371. if (this._sound !== undefined)
  36372. this._sound.stop();
  36373. };
  36374. StopSoundAction.prototype.serialize = function (parent) {
  36375. return _super.prototype._serialize.call(this, {
  36376. name: "StopSoundAction",
  36377. properties: [{ name: "sound", value: this._sound.name }]
  36378. }, parent);
  36379. };
  36380. return StopSoundAction;
  36381. }(BABYLON.Action));
  36382. BABYLON.StopSoundAction = StopSoundAction;
  36383. })(BABYLON || (BABYLON = {}));
  36384. //# sourceMappingURL=babylon.directActions.js.map
  36385. var BABYLON;
  36386. (function (BABYLON) {
  36387. var SpriteManager = (function () {
  36388. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  36389. if (epsilon === void 0) { epsilon = 0.01; }
  36390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  36391. this.name = name;
  36392. this.sprites = new Array();
  36393. this.renderingGroupId = 0;
  36394. this.layerMask = 0x0FFFFFFF;
  36395. this.fogEnabled = true;
  36396. this.isPickable = false;
  36397. /**
  36398. * An event triggered when the manager is disposed.
  36399. * @type {BABYLON.Observable}
  36400. */
  36401. this.onDisposeObservable = new BABYLON.Observable();
  36402. this._vertexBuffers = {};
  36403. this._capacity = capacity;
  36404. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  36405. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36406. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  36407. if (cellSize.width && cellSize.height) {
  36408. this.cellWidth = cellSize.width;
  36409. this.cellHeight = cellSize.height;
  36410. }
  36411. else if (cellSize !== undefined) {
  36412. this.cellWidth = cellSize;
  36413. this.cellHeight = cellSize;
  36414. }
  36415. else {
  36416. return;
  36417. }
  36418. this._epsilon = epsilon;
  36419. this._scene = scene;
  36420. this._scene.spriteManagers.push(this);
  36421. var indices = [];
  36422. var index = 0;
  36423. for (var count = 0; count < capacity; count++) {
  36424. indices.push(index);
  36425. indices.push(index + 1);
  36426. indices.push(index + 2);
  36427. indices.push(index);
  36428. indices.push(index + 2);
  36429. indices.push(index + 3);
  36430. index += 4;
  36431. }
  36432. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36433. // VBO
  36434. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  36435. this._vertexData = new Float32Array(capacity * 16 * 4);
  36436. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  36437. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  36438. var options = this._buffer.createVertexBuffer("options", 4, 4);
  36439. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  36440. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  36441. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36442. this._vertexBuffers["options"] = options;
  36443. this._vertexBuffers["cellInfo"] = cellInfo;
  36444. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36445. // Effects
  36446. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  36447. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  36448. }
  36449. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  36450. set: function (callback) {
  36451. if (this._onDisposeObserver) {
  36452. this.onDisposeObservable.remove(this._onDisposeObserver);
  36453. }
  36454. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36455. },
  36456. enumerable: true,
  36457. configurable: true
  36458. });
  36459. Object.defineProperty(SpriteManager.prototype, "texture", {
  36460. get: function () {
  36461. return this._spriteTexture;
  36462. },
  36463. set: function (value) {
  36464. this._spriteTexture = value;
  36465. },
  36466. enumerable: true,
  36467. configurable: true
  36468. });
  36469. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  36470. var arrayOffset = index * 16;
  36471. if (offsetX === 0)
  36472. offsetX = this._epsilon;
  36473. else if (offsetX === 1)
  36474. offsetX = 1 - this._epsilon;
  36475. if (offsetY === 0)
  36476. offsetY = this._epsilon;
  36477. else if (offsetY === 1)
  36478. offsetY = 1 - this._epsilon;
  36479. this._vertexData[arrayOffset] = sprite.position.x;
  36480. this._vertexData[arrayOffset + 1] = sprite.position.y;
  36481. this._vertexData[arrayOffset + 2] = sprite.position.z;
  36482. this._vertexData[arrayOffset + 3] = sprite.angle;
  36483. this._vertexData[arrayOffset + 4] = sprite.width;
  36484. this._vertexData[arrayOffset + 5] = sprite.height;
  36485. this._vertexData[arrayOffset + 6] = offsetX;
  36486. this._vertexData[arrayOffset + 7] = offsetY;
  36487. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  36488. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  36489. var offset = (sprite.cellIndex / rowSize) >> 0;
  36490. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  36491. this._vertexData[arrayOffset + 11] = offset;
  36492. // Color
  36493. this._vertexData[arrayOffset + 12] = sprite.color.r;
  36494. this._vertexData[arrayOffset + 13] = sprite.color.g;
  36495. this._vertexData[arrayOffset + 14] = sprite.color.b;
  36496. this._vertexData[arrayOffset + 15] = sprite.color.a;
  36497. };
  36498. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  36499. var count = Math.min(this._capacity, this.sprites.length);
  36500. var min = BABYLON.Vector3.Zero();
  36501. var max = BABYLON.Vector3.Zero();
  36502. var distance = Number.MAX_VALUE;
  36503. var currentSprite;
  36504. var cameraSpacePosition = BABYLON.Vector3.Zero();
  36505. var cameraView = camera.getViewMatrix();
  36506. for (var index = 0; index < count; index++) {
  36507. var sprite = this.sprites[index];
  36508. if (!sprite) {
  36509. continue;
  36510. }
  36511. if (predicate) {
  36512. if (!predicate(sprite)) {
  36513. continue;
  36514. }
  36515. }
  36516. else if (!sprite.isPickable) {
  36517. continue;
  36518. }
  36519. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  36520. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  36521. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  36522. if (ray.intersectsBoxMinMax(min, max)) {
  36523. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  36524. if (distance > currentDistance) {
  36525. distance = currentDistance;
  36526. currentSprite = sprite;
  36527. if (fastCheck) {
  36528. break;
  36529. }
  36530. }
  36531. }
  36532. }
  36533. if (currentSprite) {
  36534. var result = new BABYLON.PickingInfo();
  36535. result.hit = true;
  36536. result.pickedSprite = currentSprite;
  36537. result.distance = distance;
  36538. return result;
  36539. }
  36540. return null;
  36541. };
  36542. SpriteManager.prototype.render = function () {
  36543. // Check
  36544. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  36545. return;
  36546. var engine = this._scene.getEngine();
  36547. var baseSize = this._spriteTexture.getBaseSize();
  36548. // Sprites
  36549. var deltaTime = engine.getDeltaTime();
  36550. var max = Math.min(this._capacity, this.sprites.length);
  36551. var rowSize = baseSize.width / this.cellWidth;
  36552. var offset = 0;
  36553. for (var index = 0; index < max; index++) {
  36554. var sprite = this.sprites[index];
  36555. if (!sprite) {
  36556. continue;
  36557. }
  36558. sprite._animate(deltaTime);
  36559. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  36560. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  36561. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  36562. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  36563. }
  36564. this._buffer.update(this._vertexData);
  36565. // Render
  36566. var effect = this._effectBase;
  36567. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36568. effect = this._effectFog;
  36569. }
  36570. engine.enableEffect(effect);
  36571. var viewMatrix = this._scene.getViewMatrix();
  36572. effect.setTexture("diffuseSampler", this._spriteTexture);
  36573. effect.setMatrix("view", viewMatrix);
  36574. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36575. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  36576. // Fog
  36577. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  36578. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  36579. effect.setColor3("vFogColor", this._scene.fogColor);
  36580. }
  36581. // VBOs
  36582. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36583. // Draw order
  36584. engine.setDepthFunctionToLessOrEqual();
  36585. effect.setBool("alphaTest", true);
  36586. engine.setColorWrite(false);
  36587. engine.draw(true, 0, max * 6);
  36588. engine.setColorWrite(true);
  36589. effect.setBool("alphaTest", false);
  36590. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36591. engine.draw(true, 0, max * 6);
  36592. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36593. };
  36594. SpriteManager.prototype.dispose = function () {
  36595. if (this._buffer) {
  36596. this._buffer.dispose();
  36597. this._buffer = null;
  36598. }
  36599. if (this._indexBuffer) {
  36600. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36601. this._indexBuffer = null;
  36602. }
  36603. if (this._spriteTexture) {
  36604. this._spriteTexture.dispose();
  36605. this._spriteTexture = null;
  36606. }
  36607. // Remove from scene
  36608. var index = this._scene.spriteManagers.indexOf(this);
  36609. this._scene.spriteManagers.splice(index, 1);
  36610. // Callback
  36611. this.onDisposeObservable.notifyObservers(this);
  36612. this.onDisposeObservable.clear();
  36613. };
  36614. return SpriteManager;
  36615. }());
  36616. BABYLON.SpriteManager = SpriteManager;
  36617. })(BABYLON || (BABYLON = {}));
  36618. //# sourceMappingURL=babylon.spriteManager.js.map
  36619. var BABYLON;
  36620. (function (BABYLON) {
  36621. var Sprite = (function () {
  36622. function Sprite(name, manager) {
  36623. this.name = name;
  36624. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36625. this.width = 1.0;
  36626. this.height = 1.0;
  36627. this.angle = 0;
  36628. this.cellIndex = 0;
  36629. this.invertU = 0;
  36630. this.invertV = 0;
  36631. this.animations = new Array();
  36632. this.isPickable = false;
  36633. this._animationStarted = false;
  36634. this._loopAnimation = false;
  36635. this._fromIndex = 0;
  36636. this._toIndex = 0;
  36637. this._delay = 0;
  36638. this._direction = 1;
  36639. this._frameCount = 0;
  36640. this._time = 0;
  36641. this._manager = manager;
  36642. this._manager.sprites.push(this);
  36643. this.position = BABYLON.Vector3.Zero();
  36644. }
  36645. Object.defineProperty(Sprite.prototype, "size", {
  36646. get: function () {
  36647. return this.width;
  36648. },
  36649. set: function (value) {
  36650. this.width = value;
  36651. this.height = value;
  36652. },
  36653. enumerable: true,
  36654. configurable: true
  36655. });
  36656. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  36657. this._fromIndex = from;
  36658. this._toIndex = to;
  36659. this._loopAnimation = loop;
  36660. this._delay = delay;
  36661. this._animationStarted = true;
  36662. this._direction = from < to ? 1 : -1;
  36663. this.cellIndex = from;
  36664. this._time = 0;
  36665. this._onAnimationEnd = onAnimationEnd;
  36666. };
  36667. Sprite.prototype.stopAnimation = function () {
  36668. this._animationStarted = false;
  36669. };
  36670. Sprite.prototype._animate = function (deltaTime) {
  36671. if (!this._animationStarted)
  36672. return;
  36673. this._time += deltaTime;
  36674. if (this._time > this._delay) {
  36675. this._time = this._time % this._delay;
  36676. this.cellIndex += this._direction;
  36677. if (this.cellIndex === this._toIndex) {
  36678. if (this._loopAnimation) {
  36679. this.cellIndex = this._fromIndex;
  36680. }
  36681. else {
  36682. this._animationStarted = false;
  36683. if (this._onAnimationEnd) {
  36684. this._onAnimationEnd();
  36685. }
  36686. if (this.disposeWhenFinishedAnimating) {
  36687. this.dispose();
  36688. }
  36689. }
  36690. }
  36691. }
  36692. };
  36693. Sprite.prototype.dispose = function () {
  36694. for (var i = 0; i < this._manager.sprites.length; i++) {
  36695. if (this._manager.sprites[i] == this) {
  36696. this._manager.sprites.splice(i, 1);
  36697. }
  36698. }
  36699. };
  36700. return Sprite;
  36701. }());
  36702. BABYLON.Sprite = Sprite;
  36703. })(BABYLON || (BABYLON = {}));
  36704. //# sourceMappingURL=babylon.sprite.js.map
  36705. var BABYLON;
  36706. (function (BABYLON) {
  36707. var IntersectionInfo = (function () {
  36708. function IntersectionInfo(bu, bv, distance) {
  36709. this.bu = bu;
  36710. this.bv = bv;
  36711. this.distance = distance;
  36712. this.faceId = 0;
  36713. this.subMeshId = 0;
  36714. }
  36715. return IntersectionInfo;
  36716. }());
  36717. BABYLON.IntersectionInfo = IntersectionInfo;
  36718. var PickingInfo = (function () {
  36719. function PickingInfo() {
  36720. this.hit = false;
  36721. this.distance = 0;
  36722. this.pickedPoint = null;
  36723. this.pickedMesh = null;
  36724. this.bu = 0;
  36725. this.bv = 0;
  36726. this.faceId = -1;
  36727. this.subMeshId = 0;
  36728. this.pickedSprite = null;
  36729. }
  36730. // Methods
  36731. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  36732. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  36733. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  36734. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36735. return null;
  36736. }
  36737. var indices = this.pickedMesh.getIndices();
  36738. var result;
  36739. if (useVerticesNormals) {
  36740. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36741. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  36742. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  36743. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  36744. normal0 = normal0.scale(this.bu);
  36745. normal1 = normal1.scale(this.bv);
  36746. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  36747. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  36748. }
  36749. else {
  36750. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36751. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  36752. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  36753. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  36754. var p1p2 = vertex1.subtract(vertex2);
  36755. var p3p2 = vertex3.subtract(vertex2);
  36756. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  36757. }
  36758. if (useWorldCoordinates) {
  36759. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  36760. }
  36761. return BABYLON.Vector3.Normalize(result);
  36762. };
  36763. PickingInfo.prototype.getTextureCoordinates = function () {
  36764. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36765. return null;
  36766. }
  36767. var indices = this.pickedMesh.getIndices();
  36768. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36769. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  36770. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  36771. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  36772. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  36773. uv1 = uv1.scale(this.bu);
  36774. uv2 = uv2.scale(this.bv);
  36775. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  36776. };
  36777. return PickingInfo;
  36778. }());
  36779. BABYLON.PickingInfo = PickingInfo;
  36780. })(BABYLON || (BABYLON = {}));
  36781. //# sourceMappingURL=babylon.pickingInfo.js.map
  36782. var BABYLON;
  36783. (function (BABYLON) {
  36784. var Ray = (function () {
  36785. function Ray(origin, direction, length) {
  36786. if (length === void 0) { length = Number.MAX_VALUE; }
  36787. this.origin = origin;
  36788. this.direction = direction;
  36789. this.length = length;
  36790. }
  36791. // Methods
  36792. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  36793. var d = 0.0;
  36794. var maxValue = Number.MAX_VALUE;
  36795. var inv;
  36796. var min;
  36797. var max;
  36798. var temp;
  36799. if (Math.abs(this.direction.x) < 0.0000001) {
  36800. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  36801. return false;
  36802. }
  36803. }
  36804. else {
  36805. inv = 1.0 / this.direction.x;
  36806. min = (minimum.x - this.origin.x) * inv;
  36807. max = (maximum.x - this.origin.x) * inv;
  36808. if (max === -Infinity) {
  36809. max = Infinity;
  36810. }
  36811. if (min > max) {
  36812. temp = min;
  36813. min = max;
  36814. max = temp;
  36815. }
  36816. d = Math.max(min, d);
  36817. maxValue = Math.min(max, maxValue);
  36818. if (d > maxValue) {
  36819. return false;
  36820. }
  36821. }
  36822. if (Math.abs(this.direction.y) < 0.0000001) {
  36823. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  36824. return false;
  36825. }
  36826. }
  36827. else {
  36828. inv = 1.0 / this.direction.y;
  36829. min = (minimum.y - this.origin.y) * inv;
  36830. max = (maximum.y - this.origin.y) * inv;
  36831. if (max === -Infinity) {
  36832. max = Infinity;
  36833. }
  36834. if (min > max) {
  36835. temp = min;
  36836. min = max;
  36837. max = temp;
  36838. }
  36839. d = Math.max(min, d);
  36840. maxValue = Math.min(max, maxValue);
  36841. if (d > maxValue) {
  36842. return false;
  36843. }
  36844. }
  36845. if (Math.abs(this.direction.z) < 0.0000001) {
  36846. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  36847. return false;
  36848. }
  36849. }
  36850. else {
  36851. inv = 1.0 / this.direction.z;
  36852. min = (minimum.z - this.origin.z) * inv;
  36853. max = (maximum.z - this.origin.z) * inv;
  36854. if (max === -Infinity) {
  36855. max = Infinity;
  36856. }
  36857. if (min > max) {
  36858. temp = min;
  36859. min = max;
  36860. max = temp;
  36861. }
  36862. d = Math.max(min, d);
  36863. maxValue = Math.min(max, maxValue);
  36864. if (d > maxValue) {
  36865. return false;
  36866. }
  36867. }
  36868. return true;
  36869. };
  36870. Ray.prototype.intersectsBox = function (box) {
  36871. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  36872. };
  36873. Ray.prototype.intersectsSphere = function (sphere) {
  36874. var x = sphere.center.x - this.origin.x;
  36875. var y = sphere.center.y - this.origin.y;
  36876. var z = sphere.center.z - this.origin.z;
  36877. var pyth = (x * x) + (y * y) + (z * z);
  36878. var rr = sphere.radius * sphere.radius;
  36879. if (pyth <= rr) {
  36880. return true;
  36881. }
  36882. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  36883. if (dot < 0.0) {
  36884. return false;
  36885. }
  36886. var temp = pyth - (dot * dot);
  36887. return temp <= rr;
  36888. };
  36889. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  36890. if (!this._edge1) {
  36891. this._edge1 = BABYLON.Vector3.Zero();
  36892. this._edge2 = BABYLON.Vector3.Zero();
  36893. this._pvec = BABYLON.Vector3.Zero();
  36894. this._tvec = BABYLON.Vector3.Zero();
  36895. this._qvec = BABYLON.Vector3.Zero();
  36896. }
  36897. vertex1.subtractToRef(vertex0, this._edge1);
  36898. vertex2.subtractToRef(vertex0, this._edge2);
  36899. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  36900. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  36901. if (det === 0) {
  36902. return null;
  36903. }
  36904. var invdet = 1 / det;
  36905. this.origin.subtractToRef(vertex0, this._tvec);
  36906. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  36907. if (bu < 0 || bu > 1.0) {
  36908. return null;
  36909. }
  36910. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  36911. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  36912. if (bv < 0 || bu + bv > 1.0) {
  36913. return null;
  36914. }
  36915. //check if the distance is longer than the predefined length.
  36916. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  36917. if (distance > this.length) {
  36918. return null;
  36919. }
  36920. return new BABYLON.IntersectionInfo(bu, bv, distance);
  36921. };
  36922. Ray.prototype.intersectsPlane = function (plane) {
  36923. var distance;
  36924. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  36925. if (Math.abs(result1) < 9.99999997475243E-07) {
  36926. return null;
  36927. }
  36928. else {
  36929. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  36930. distance = (-plane.d - result2) / result1;
  36931. if (distance < 0.0) {
  36932. if (distance < -9.99999997475243E-07) {
  36933. return null;
  36934. }
  36935. else {
  36936. return 0;
  36937. }
  36938. }
  36939. return distance;
  36940. }
  36941. };
  36942. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  36943. var tm = BABYLON.Tmp.Matrix[0];
  36944. mesh.getWorldMatrix().invertToRef(tm);
  36945. if (this._tmpRay) {
  36946. Ray.TransformToRef(this, tm, this._tmpRay);
  36947. }
  36948. else {
  36949. this._tmpRay = Ray.Transform(this, tm);
  36950. }
  36951. return mesh.intersects(this._tmpRay, fastCheck);
  36952. };
  36953. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  36954. if (results) {
  36955. results.length = 0;
  36956. }
  36957. else {
  36958. results = [];
  36959. }
  36960. for (var i = 0; i < meshes.length; i++) {
  36961. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  36962. if (pickInfo.hit) {
  36963. results.push(pickInfo);
  36964. }
  36965. }
  36966. results.sort(this._comparePickingInfo);
  36967. return results;
  36968. };
  36969. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  36970. if (pickingInfoA.distance < pickingInfoB.distance) {
  36971. return -1;
  36972. }
  36973. else if (pickingInfoA.distance > pickingInfoB.distance) {
  36974. return 1;
  36975. }
  36976. else {
  36977. return 0;
  36978. }
  36979. };
  36980. /**
  36981. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  36982. * @param sega the first point of the segment to test the intersection against
  36983. * @param segb the second point of the segment to test the intersection against
  36984. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  36985. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  36986. */
  36987. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  36988. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  36989. var u = segb.subtract(sega);
  36990. var v = rsegb.subtract(this.origin);
  36991. var w = sega.subtract(this.origin);
  36992. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  36993. var b = BABYLON.Vector3.Dot(u, v);
  36994. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  36995. var d = BABYLON.Vector3.Dot(u, w);
  36996. var e = BABYLON.Vector3.Dot(v, w);
  36997. var D = a * c - b * b; // always >= 0
  36998. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  36999. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  37000. // compute the line parameters of the two closest points
  37001. if (D < Ray.smallnum) {
  37002. sN = 0.0; // force using point P0 on segment S1
  37003. sD = 1.0; // to prevent possible division by 0.0 later
  37004. tN = e;
  37005. tD = c;
  37006. }
  37007. else {
  37008. sN = (b * e - c * d);
  37009. tN = (a * e - b * d);
  37010. if (sN < 0.0) {
  37011. sN = 0.0;
  37012. tN = e;
  37013. tD = c;
  37014. }
  37015. else if (sN > sD) {
  37016. sN = sD;
  37017. tN = e + b;
  37018. tD = c;
  37019. }
  37020. }
  37021. if (tN < 0.0) {
  37022. tN = 0.0;
  37023. // recompute sc for this edge
  37024. if (-d < 0.0) {
  37025. sN = 0.0;
  37026. }
  37027. else if (-d > a)
  37028. sN = sD;
  37029. else {
  37030. sN = -d;
  37031. sD = a;
  37032. }
  37033. }
  37034. else if (tN > tD) {
  37035. tN = tD;
  37036. // recompute sc for this edge
  37037. if ((-d + b) < 0.0) {
  37038. sN = 0;
  37039. }
  37040. else if ((-d + b) > a) {
  37041. sN = sD;
  37042. }
  37043. else {
  37044. sN = (-d + b);
  37045. sD = a;
  37046. }
  37047. }
  37048. // finally do the division to get sc and tc
  37049. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  37050. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  37051. // get the difference of the two closest points
  37052. var qtc = v.multiplyByFloats(tc, tc, tc);
  37053. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  37054. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  37055. if (isIntersected) {
  37056. return qtc.length();
  37057. }
  37058. return -1;
  37059. };
  37060. // Statics
  37061. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  37062. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  37063. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  37064. var direction = end.subtract(start);
  37065. direction.normalize();
  37066. return new Ray(start, direction);
  37067. };
  37068. /**
  37069. * 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
  37070. * transformed to the given world matrix.
  37071. * @param origin The origin point
  37072. * @param end The end point
  37073. * @param world a matrix to transform the ray to. Default is the identity matrix.
  37074. */
  37075. Ray.CreateNewFromTo = function (origin, end, world) {
  37076. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  37077. var direction = end.subtract(origin);
  37078. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  37079. direction.normalize();
  37080. return Ray.Transform(new Ray(origin, direction, length), world);
  37081. };
  37082. Ray.Transform = function (ray, matrix) {
  37083. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  37084. Ray.TransformToRef(ray, matrix, result);
  37085. return result;
  37086. };
  37087. Ray.TransformToRef = function (ray, matrix, result) {
  37088. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  37089. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  37090. result.length = ray.length;
  37091. var dir = result.direction;
  37092. var len = dir.length();
  37093. if (!(len === 0 || len === 1)) {
  37094. var num = 1.0 / len;
  37095. dir.x *= num;
  37096. dir.y *= num;
  37097. dir.z *= num;
  37098. result.length *= len;
  37099. }
  37100. };
  37101. return Ray;
  37102. }());
  37103. Ray.smallnum = 0.00000001;
  37104. Ray.rayl = 10e8;
  37105. BABYLON.Ray = Ray;
  37106. })(BABYLON || (BABYLON = {}));
  37107. //# sourceMappingURL=babylon.ray.js.map
  37108. var BABYLON;
  37109. (function (BABYLON) {
  37110. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  37111. if (boxMin.x > sphereCenter.x + sphereRadius)
  37112. return false;
  37113. if (sphereCenter.x - sphereRadius > boxMax.x)
  37114. return false;
  37115. if (boxMin.y > sphereCenter.y + sphereRadius)
  37116. return false;
  37117. if (sphereCenter.y - sphereRadius > boxMax.y)
  37118. return false;
  37119. if (boxMin.z > sphereCenter.z + sphereRadius)
  37120. return false;
  37121. if (sphereCenter.z - sphereRadius > boxMax.z)
  37122. return false;
  37123. return true;
  37124. };
  37125. var getLowestRoot = (function () {
  37126. var result = { root: 0, found: false };
  37127. return function (a, b, c, maxR) {
  37128. result.root = 0;
  37129. result.found = false;
  37130. var determinant = b * b - 4.0 * a * c;
  37131. if (determinant < 0)
  37132. return result;
  37133. var sqrtD = Math.sqrt(determinant);
  37134. var r1 = (-b - sqrtD) / (2.0 * a);
  37135. var r2 = (-b + sqrtD) / (2.0 * a);
  37136. if (r1 > r2) {
  37137. var temp = r2;
  37138. r2 = r1;
  37139. r1 = temp;
  37140. }
  37141. if (r1 > 0 && r1 < maxR) {
  37142. result.root = r1;
  37143. result.found = true;
  37144. return result;
  37145. }
  37146. if (r2 > 0 && r2 < maxR) {
  37147. result.root = r2;
  37148. result.found = true;
  37149. return result;
  37150. }
  37151. return result;
  37152. };
  37153. })();
  37154. var Collider = (function () {
  37155. function Collider() {
  37156. this.radius = BABYLON.Vector3.One();
  37157. this.retry = 0;
  37158. this.basePointWorld = BABYLON.Vector3.Zero();
  37159. this.velocityWorld = BABYLON.Vector3.Zero();
  37160. this.normalizedVelocity = BABYLON.Vector3.Zero();
  37161. this._collisionPoint = BABYLON.Vector3.Zero();
  37162. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  37163. this._tempVector = BABYLON.Vector3.Zero();
  37164. this._tempVector2 = BABYLON.Vector3.Zero();
  37165. this._tempVector3 = BABYLON.Vector3.Zero();
  37166. this._tempVector4 = BABYLON.Vector3.Zero();
  37167. this._edge = BABYLON.Vector3.Zero();
  37168. this._baseToVertex = BABYLON.Vector3.Zero();
  37169. this._destinationPoint = BABYLON.Vector3.Zero();
  37170. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  37171. this._displacementVector = BABYLON.Vector3.Zero();
  37172. this._collisionMask = -1;
  37173. }
  37174. Object.defineProperty(Collider.prototype, "collisionMask", {
  37175. get: function () {
  37176. return this._collisionMask;
  37177. },
  37178. set: function (mask) {
  37179. this._collisionMask = !isNaN(mask) ? mask : -1;
  37180. },
  37181. enumerable: true,
  37182. configurable: true
  37183. });
  37184. // Methods
  37185. Collider.prototype._initialize = function (source, dir, e) {
  37186. this.velocity = dir;
  37187. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  37188. this.basePoint = source;
  37189. source.multiplyToRef(this.radius, this.basePointWorld);
  37190. dir.multiplyToRef(this.radius, this.velocityWorld);
  37191. this.velocityWorldLength = this.velocityWorld.length();
  37192. this.epsilon = e;
  37193. this.collisionFound = false;
  37194. };
  37195. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  37196. pa.subtractToRef(point, this._tempVector);
  37197. pb.subtractToRef(point, this._tempVector2);
  37198. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  37199. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37200. if (d < 0)
  37201. return false;
  37202. pc.subtractToRef(point, this._tempVector3);
  37203. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  37204. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37205. if (d < 0)
  37206. return false;
  37207. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  37208. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  37209. return d >= 0;
  37210. };
  37211. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  37212. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  37213. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  37214. if (distance > this.velocityWorldLength + max + sphereRadius) {
  37215. return false;
  37216. }
  37217. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  37218. return false;
  37219. return true;
  37220. };
  37221. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  37222. var t0;
  37223. var embeddedInPlane = false;
  37224. //defensive programming, actually not needed.
  37225. if (!trianglePlaneArray) {
  37226. trianglePlaneArray = [];
  37227. }
  37228. if (!trianglePlaneArray[faceIndex]) {
  37229. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  37230. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  37231. }
  37232. var trianglePlane = trianglePlaneArray[faceIndex];
  37233. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  37234. return;
  37235. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  37236. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  37237. if (normalDotVelocity == 0) {
  37238. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  37239. return;
  37240. embeddedInPlane = true;
  37241. t0 = 0;
  37242. }
  37243. else {
  37244. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37245. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  37246. if (t0 > t1) {
  37247. var temp = t1;
  37248. t1 = t0;
  37249. t0 = temp;
  37250. }
  37251. if (t0 > 1.0 || t1 < 0.0)
  37252. return;
  37253. if (t0 < 0)
  37254. t0 = 0;
  37255. if (t0 > 1.0)
  37256. t0 = 1.0;
  37257. }
  37258. this._collisionPoint.copyFromFloats(0, 0, 0);
  37259. var found = false;
  37260. var t = 1.0;
  37261. if (!embeddedInPlane) {
  37262. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  37263. this.velocity.scaleToRef(t0, this._tempVector);
  37264. this._planeIntersectionPoint.addInPlace(this._tempVector);
  37265. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  37266. found = true;
  37267. t = t0;
  37268. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  37269. }
  37270. }
  37271. if (!found) {
  37272. var velocitySquaredLength = this.velocity.lengthSquared();
  37273. var a = velocitySquaredLength;
  37274. this.basePoint.subtractToRef(p1, this._tempVector);
  37275. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37276. var c = this._tempVector.lengthSquared() - 1.0;
  37277. var lowestRoot = getLowestRoot(a, b, c, t);
  37278. if (lowestRoot.found) {
  37279. t = lowestRoot.root;
  37280. found = true;
  37281. this._collisionPoint.copyFrom(p1);
  37282. }
  37283. this.basePoint.subtractToRef(p2, this._tempVector);
  37284. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37285. c = this._tempVector.lengthSquared() - 1.0;
  37286. lowestRoot = getLowestRoot(a, b, c, t);
  37287. if (lowestRoot.found) {
  37288. t = lowestRoot.root;
  37289. found = true;
  37290. this._collisionPoint.copyFrom(p2);
  37291. }
  37292. this.basePoint.subtractToRef(p3, this._tempVector);
  37293. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  37294. c = this._tempVector.lengthSquared() - 1.0;
  37295. lowestRoot = getLowestRoot(a, b, c, t);
  37296. if (lowestRoot.found) {
  37297. t = lowestRoot.root;
  37298. found = true;
  37299. this._collisionPoint.copyFrom(p3);
  37300. }
  37301. p2.subtractToRef(p1, this._edge);
  37302. p1.subtractToRef(this.basePoint, this._baseToVertex);
  37303. var edgeSquaredLength = this._edge.lengthSquared();
  37304. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37305. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37306. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37307. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37308. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37309. lowestRoot = getLowestRoot(a, b, c, t);
  37310. if (lowestRoot.found) {
  37311. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37312. if (f >= 0.0 && f <= 1.0) {
  37313. t = lowestRoot.root;
  37314. found = true;
  37315. this._edge.scaleInPlace(f);
  37316. p1.addToRef(this._edge, this._collisionPoint);
  37317. }
  37318. }
  37319. p3.subtractToRef(p2, this._edge);
  37320. p2.subtractToRef(this.basePoint, this._baseToVertex);
  37321. edgeSquaredLength = this._edge.lengthSquared();
  37322. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37323. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37324. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37325. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37326. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37327. lowestRoot = getLowestRoot(a, b, c, t);
  37328. if (lowestRoot.found) {
  37329. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37330. if (f >= 0.0 && f <= 1.0) {
  37331. t = lowestRoot.root;
  37332. found = true;
  37333. this._edge.scaleInPlace(f);
  37334. p2.addToRef(this._edge, this._collisionPoint);
  37335. }
  37336. }
  37337. p1.subtractToRef(p3, this._edge);
  37338. p3.subtractToRef(this.basePoint, this._baseToVertex);
  37339. edgeSquaredLength = this._edge.lengthSquared();
  37340. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  37341. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  37342. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  37343. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  37344. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  37345. lowestRoot = getLowestRoot(a, b, c, t);
  37346. if (lowestRoot.found) {
  37347. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  37348. if (f >= 0.0 && f <= 1.0) {
  37349. t = lowestRoot.root;
  37350. found = true;
  37351. this._edge.scaleInPlace(f);
  37352. p3.addToRef(this._edge, this._collisionPoint);
  37353. }
  37354. }
  37355. }
  37356. if (found) {
  37357. var distToCollision = t * this.velocity.length();
  37358. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  37359. if (!this.intersectionPoint) {
  37360. this.intersectionPoint = this._collisionPoint.clone();
  37361. }
  37362. else {
  37363. this.intersectionPoint.copyFrom(this._collisionPoint);
  37364. }
  37365. this.nearestDistance = distToCollision;
  37366. this.collisionFound = true;
  37367. }
  37368. }
  37369. };
  37370. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  37371. for (var i = indexStart; i < indexEnd; i += 3) {
  37372. var p1 = pts[indices[i] - decal];
  37373. var p2 = pts[indices[i + 1] - decal];
  37374. var p3 = pts[indices[i + 2] - decal];
  37375. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  37376. }
  37377. };
  37378. Collider.prototype._getResponse = function (pos, vel) {
  37379. pos.addToRef(vel, this._destinationPoint);
  37380. vel.scaleInPlace((this.nearestDistance / vel.length()));
  37381. this.basePoint.addToRef(vel, pos);
  37382. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  37383. this._slidePlaneNormal.normalize();
  37384. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  37385. pos.addInPlace(this._displacementVector);
  37386. this.intersectionPoint.addInPlace(this._displacementVector);
  37387. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  37388. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  37389. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  37390. };
  37391. return Collider;
  37392. }());
  37393. BABYLON.Collider = Collider;
  37394. })(BABYLON || (BABYLON = {}));
  37395. //# sourceMappingURL=babylon.collider.js.map
  37396. var BABYLON;
  37397. (function (BABYLON) {
  37398. //WebWorker code will be inserted to this variable.
  37399. BABYLON.CollisionWorker = "";
  37400. var WorkerTaskType;
  37401. (function (WorkerTaskType) {
  37402. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  37403. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  37404. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  37405. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  37406. var WorkerReplyType;
  37407. (function (WorkerReplyType) {
  37408. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  37409. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  37410. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  37411. var CollisionCoordinatorWorker = (function () {
  37412. function CollisionCoordinatorWorker() {
  37413. var _this = this;
  37414. this._scaledPosition = BABYLON.Vector3.Zero();
  37415. this._scaledVelocity = BABYLON.Vector3.Zero();
  37416. this.onMeshUpdated = function (mesh) {
  37417. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  37418. };
  37419. this.onGeometryUpdated = function (geometry) {
  37420. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  37421. };
  37422. this._afterRender = function () {
  37423. if (!_this._init)
  37424. return;
  37425. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  37426. return;
  37427. }
  37428. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  37429. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  37430. if (_this._runningUpdated > 4) {
  37431. return;
  37432. }
  37433. ++_this._runningUpdated;
  37434. var payload = {
  37435. updatedMeshes: _this._addUpdateMeshesList,
  37436. updatedGeometries: _this._addUpdateGeometriesList,
  37437. removedGeometries: _this._toRemoveGeometryArray,
  37438. removedMeshes: _this._toRemoveMeshesArray
  37439. };
  37440. var message = {
  37441. payload: payload,
  37442. taskType: WorkerTaskType.UPDATE
  37443. };
  37444. var serializable = [];
  37445. for (var id in payload.updatedGeometries) {
  37446. if (payload.updatedGeometries.hasOwnProperty(id)) {
  37447. //prepare transferables
  37448. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  37449. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  37450. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  37451. }
  37452. }
  37453. _this._worker.postMessage(message, serializable);
  37454. _this._addUpdateMeshesList = {};
  37455. _this._addUpdateGeometriesList = {};
  37456. _this._toRemoveGeometryArray = [];
  37457. _this._toRemoveMeshesArray = [];
  37458. };
  37459. this._onMessageFromWorker = function (e) {
  37460. var returnData = e.data;
  37461. if (returnData.error != WorkerReplyType.SUCCESS) {
  37462. //TODO what errors can be returned from the worker?
  37463. BABYLON.Tools.Warn("error returned from worker!");
  37464. return;
  37465. }
  37466. switch (returnData.taskType) {
  37467. case WorkerTaskType.INIT:
  37468. _this._init = true;
  37469. //Update the worked with ALL of the scene's current state
  37470. _this._scene.meshes.forEach(function (mesh) {
  37471. _this.onMeshAdded(mesh);
  37472. });
  37473. _this._scene.getGeometries().forEach(function (geometry) {
  37474. _this.onGeometryAdded(geometry);
  37475. });
  37476. break;
  37477. case WorkerTaskType.UPDATE:
  37478. _this._runningUpdated--;
  37479. break;
  37480. case WorkerTaskType.COLLIDE:
  37481. _this._runningCollisionTask = false;
  37482. var returnPayload = returnData.payload;
  37483. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  37484. return;
  37485. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  37486. //cleanup
  37487. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  37488. break;
  37489. }
  37490. };
  37491. this._collisionsCallbackArray = [];
  37492. this._init = false;
  37493. this._runningUpdated = 0;
  37494. this._runningCollisionTask = false;
  37495. this._addUpdateMeshesList = {};
  37496. this._addUpdateGeometriesList = {};
  37497. this._toRemoveGeometryArray = [];
  37498. this._toRemoveMeshesArray = [];
  37499. }
  37500. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37501. if (!this._init)
  37502. return;
  37503. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  37504. return;
  37505. position.divideToRef(collider.radius, this._scaledPosition);
  37506. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37507. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  37508. var payload = {
  37509. collider: {
  37510. position: this._scaledPosition.asArray(),
  37511. velocity: this._scaledVelocity.asArray(),
  37512. radius: collider.radius.asArray()
  37513. },
  37514. collisionId: collisionIndex,
  37515. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  37516. maximumRetry: maximumRetry
  37517. };
  37518. var message = {
  37519. payload: payload,
  37520. taskType: WorkerTaskType.COLLIDE
  37521. };
  37522. this._worker.postMessage(message);
  37523. };
  37524. CollisionCoordinatorWorker.prototype.init = function (scene) {
  37525. this._scene = scene;
  37526. this._scene.registerAfterRender(this._afterRender);
  37527. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  37528. this._worker = new Worker(workerUrl);
  37529. this._worker.onmessage = this._onMessageFromWorker;
  37530. var message = {
  37531. payload: {},
  37532. taskType: WorkerTaskType.INIT
  37533. };
  37534. this._worker.postMessage(message);
  37535. };
  37536. CollisionCoordinatorWorker.prototype.destroy = function () {
  37537. this._scene.unregisterAfterRender(this._afterRender);
  37538. this._worker.terminate();
  37539. };
  37540. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  37541. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  37542. this.onMeshUpdated(mesh);
  37543. };
  37544. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  37545. this._toRemoveMeshesArray.push(mesh.uniqueId);
  37546. };
  37547. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  37548. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  37549. geometry.onGeometryUpdated = this.onGeometryUpdated;
  37550. this.onGeometryUpdated(geometry);
  37551. };
  37552. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  37553. this._toRemoveGeometryArray.push(geometry.id);
  37554. };
  37555. return CollisionCoordinatorWorker;
  37556. }());
  37557. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  37558. var submeshes = [];
  37559. if (mesh.subMeshes) {
  37560. submeshes = mesh.subMeshes.map(function (sm, idx) {
  37561. return {
  37562. position: idx,
  37563. verticesStart: sm.verticesStart,
  37564. verticesCount: sm.verticesCount,
  37565. indexStart: sm.indexStart,
  37566. indexCount: sm.indexCount,
  37567. hasMaterial: !!sm.getMaterial(),
  37568. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37569. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  37570. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37571. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  37572. };
  37573. });
  37574. }
  37575. var geometryId = null;
  37576. if (mesh instanceof BABYLON.Mesh) {
  37577. geometryId = mesh.geometry ? mesh.geometry.id : null;
  37578. }
  37579. else if (mesh instanceof BABYLON.InstancedMesh) {
  37580. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  37581. }
  37582. return {
  37583. uniqueId: mesh.uniqueId,
  37584. id: mesh.id,
  37585. name: mesh.name,
  37586. geometryId: geometryId,
  37587. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  37588. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  37589. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  37590. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  37591. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  37592. subMeshes: submeshes,
  37593. checkCollisions: mesh.checkCollisions
  37594. };
  37595. };
  37596. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  37597. return {
  37598. id: geometry.id,
  37599. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  37600. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  37601. indices: new Uint32Array(geometry.getIndices() || []),
  37602. };
  37603. };
  37604. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  37605. var CollisionCoordinatorLegacy = (function () {
  37606. function CollisionCoordinatorLegacy() {
  37607. this._scaledPosition = BABYLON.Vector3.Zero();
  37608. this._scaledVelocity = BABYLON.Vector3.Zero();
  37609. this._finalPosition = BABYLON.Vector3.Zero();
  37610. }
  37611. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  37612. position.divideToRef(collider.radius, this._scaledPosition);
  37613. velocity.divideToRef(collider.radius, this._scaledVelocity);
  37614. collider.collidedMesh = null;
  37615. collider.retry = 0;
  37616. collider.initialVelocity = this._scaledVelocity;
  37617. collider.initialPosition = this._scaledPosition;
  37618. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  37619. this._finalPosition.multiplyInPlace(collider.radius);
  37620. //run the callback
  37621. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  37622. };
  37623. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  37624. this._scene = scene;
  37625. };
  37626. CollisionCoordinatorLegacy.prototype.destroy = function () {
  37627. //Legacy need no destruction method.
  37628. };
  37629. //No update in legacy mode
  37630. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  37631. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  37632. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  37633. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  37634. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  37635. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  37636. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  37637. if (excludedMesh === void 0) { excludedMesh = null; }
  37638. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  37639. if (collider.retry >= maximumRetry) {
  37640. finalPosition.copyFrom(position);
  37641. return;
  37642. }
  37643. // Check if this is a mesh else camera or -1
  37644. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  37645. collider._initialize(position, velocity, closeDistance);
  37646. // Check all meshes
  37647. for (var index = 0; index < this._scene.meshes.length; index++) {
  37648. var mesh = this._scene.meshes[index];
  37649. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  37650. mesh._checkCollision(collider);
  37651. }
  37652. }
  37653. if (!collider.collisionFound) {
  37654. position.addToRef(velocity, finalPosition);
  37655. return;
  37656. }
  37657. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  37658. collider._getResponse(position, velocity);
  37659. }
  37660. if (velocity.length() <= closeDistance) {
  37661. finalPosition.copyFrom(position);
  37662. return;
  37663. }
  37664. collider.retry++;
  37665. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  37666. };
  37667. return CollisionCoordinatorLegacy;
  37668. }());
  37669. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  37670. })(BABYLON || (BABYLON = {}));
  37671. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  37672. var BABYLON;
  37673. (function (BABYLON) {
  37674. var Particle = (function () {
  37675. function Particle() {
  37676. this.position = BABYLON.Vector3.Zero();
  37677. this.direction = BABYLON.Vector3.Zero();
  37678. this.color = new BABYLON.Color4(0, 0, 0, 0);
  37679. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  37680. this.lifeTime = 1.0;
  37681. this.age = 0;
  37682. this.size = 0;
  37683. this.angle = 0;
  37684. this.angularSpeed = 0;
  37685. }
  37686. Particle.prototype.copyTo = function (other) {
  37687. other.position.copyFrom(this.position);
  37688. other.direction.copyFrom(this.direction);
  37689. other.color.copyFrom(this.color);
  37690. other.colorStep.copyFrom(this.colorStep);
  37691. other.lifeTime = this.lifeTime;
  37692. other.age = this.age;
  37693. other.size = this.size;
  37694. other.angle = this.angle;
  37695. other.angularSpeed = this.angularSpeed;
  37696. };
  37697. return Particle;
  37698. }());
  37699. BABYLON.Particle = Particle;
  37700. })(BABYLON || (BABYLON = {}));
  37701. //# sourceMappingURL=babylon.particle.js.map
  37702. var BABYLON;
  37703. (function (BABYLON) {
  37704. var randomNumber = function (min, max) {
  37705. if (min === max) {
  37706. return (min);
  37707. }
  37708. var random = Math.random();
  37709. return ((random * (max - min)) + min);
  37710. };
  37711. var ParticleSystem = (function () {
  37712. function ParticleSystem(name, capacity, scene, customEffect) {
  37713. var _this = this;
  37714. this.name = name;
  37715. // Members
  37716. this.animations = [];
  37717. this.renderingGroupId = 0;
  37718. this.emitter = null;
  37719. this.emitRate = 10;
  37720. this.manualEmitCount = -1;
  37721. this.updateSpeed = 0.01;
  37722. this.targetStopDuration = 0;
  37723. this.disposeOnStop = false;
  37724. this.minEmitPower = 1;
  37725. this.maxEmitPower = 1;
  37726. this.minLifeTime = 1;
  37727. this.maxLifeTime = 1;
  37728. this.minSize = 1;
  37729. this.maxSize = 1;
  37730. this.minAngularSpeed = 0;
  37731. this.maxAngularSpeed = 0;
  37732. this.layerMask = 0x0FFFFFFF;
  37733. this.customShader = null;
  37734. this.preventAutoStart = false;
  37735. /**
  37736. * An event triggered when the system is disposed.
  37737. * @type {BABYLON.Observable}
  37738. */
  37739. this.onDisposeObservable = new BABYLON.Observable();
  37740. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  37741. this.forceDepthWrite = false;
  37742. this.gravity = BABYLON.Vector3.Zero();
  37743. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  37744. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  37745. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  37746. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37747. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37748. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37749. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  37750. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  37751. this.particles = new Array();
  37752. this._stockParticles = new Array();
  37753. this._newPartsExcess = 0;
  37754. this._vertexBuffers = {};
  37755. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  37756. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  37757. this._scaledDirection = BABYLON.Vector3.Zero();
  37758. this._scaledGravity = BABYLON.Vector3.Zero();
  37759. this._currentRenderId = -1;
  37760. this._started = false;
  37761. this._stopped = false;
  37762. this._actualFrame = 0;
  37763. this.id = name;
  37764. this._capacity = capacity;
  37765. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37766. this._customEffect = customEffect;
  37767. scene.particleSystems.push(this);
  37768. var indices = [];
  37769. var index = 0;
  37770. for (var count = 0; count < capacity; count++) {
  37771. indices.push(index);
  37772. indices.push(index + 1);
  37773. indices.push(index + 2);
  37774. indices.push(index);
  37775. indices.push(index + 2);
  37776. indices.push(index + 3);
  37777. index += 4;
  37778. }
  37779. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  37780. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  37781. this._vertexData = new Float32Array(capacity * 11 * 4);
  37782. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  37783. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  37784. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  37785. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  37786. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  37787. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  37788. this._vertexBuffers["options"] = options;
  37789. // Default behaviors
  37790. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  37791. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  37792. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  37793. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  37794. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  37795. };
  37796. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  37797. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  37798. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  37799. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  37800. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  37801. };
  37802. this.updateFunction = function (particles) {
  37803. for (var index = 0; index < particles.length; index++) {
  37804. var particle = particles[index];
  37805. particle.age += _this._scaledUpdateSpeed;
  37806. if (particle.age >= particle.lifeTime) {
  37807. _this.recycleParticle(particle);
  37808. index--;
  37809. continue;
  37810. }
  37811. else {
  37812. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  37813. particle.color.addInPlace(_this._scaledColorStep);
  37814. if (particle.color.a < 0)
  37815. particle.color.a = 0;
  37816. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  37817. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  37818. particle.position.addInPlace(_this._scaledDirection);
  37819. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  37820. particle.direction.addInPlace(_this._scaledGravity);
  37821. }
  37822. }
  37823. };
  37824. }
  37825. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  37826. set: function (callback) {
  37827. if (this._onDisposeObserver) {
  37828. this.onDisposeObservable.remove(this._onDisposeObserver);
  37829. }
  37830. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37831. },
  37832. enumerable: true,
  37833. configurable: true
  37834. });
  37835. ParticleSystem.prototype.recycleParticle = function (particle) {
  37836. var lastParticle = this.particles.pop();
  37837. if (lastParticle !== particle) {
  37838. lastParticle.copyTo(particle);
  37839. this._stockParticles.push(lastParticle);
  37840. }
  37841. };
  37842. ParticleSystem.prototype.getCapacity = function () {
  37843. return this._capacity;
  37844. };
  37845. ParticleSystem.prototype.isAlive = function () {
  37846. return this._alive;
  37847. };
  37848. ParticleSystem.prototype.isStarted = function () {
  37849. return this._started;
  37850. };
  37851. ParticleSystem.prototype.start = function () {
  37852. this._started = true;
  37853. this._stopped = false;
  37854. this._actualFrame = 0;
  37855. };
  37856. ParticleSystem.prototype.stop = function () {
  37857. this._stopped = true;
  37858. };
  37859. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  37860. var offset = index * 11;
  37861. this._vertexData[offset] = particle.position.x;
  37862. this._vertexData[offset + 1] = particle.position.y;
  37863. this._vertexData[offset + 2] = particle.position.z;
  37864. this._vertexData[offset + 3] = particle.color.r;
  37865. this._vertexData[offset + 4] = particle.color.g;
  37866. this._vertexData[offset + 5] = particle.color.b;
  37867. this._vertexData[offset + 6] = particle.color.a;
  37868. this._vertexData[offset + 7] = particle.angle;
  37869. this._vertexData[offset + 8] = particle.size;
  37870. this._vertexData[offset + 9] = offsetX;
  37871. this._vertexData[offset + 10] = offsetY;
  37872. };
  37873. ParticleSystem.prototype._update = function (newParticles) {
  37874. // Update current
  37875. this._alive = this.particles.length > 0;
  37876. this.updateFunction(this.particles);
  37877. // Add new ones
  37878. var worldMatrix;
  37879. if (this.emitter.position) {
  37880. worldMatrix = this.emitter.getWorldMatrix();
  37881. }
  37882. else {
  37883. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  37884. }
  37885. var particle;
  37886. for (var index = 0; index < newParticles; index++) {
  37887. if (this.particles.length === this._capacity) {
  37888. break;
  37889. }
  37890. if (this._stockParticles.length !== 0) {
  37891. particle = this._stockParticles.pop();
  37892. particle.age = 0;
  37893. }
  37894. else {
  37895. particle = new BABYLON.Particle();
  37896. }
  37897. this.particles.push(particle);
  37898. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  37899. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  37900. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  37901. particle.size = randomNumber(this.minSize, this.maxSize);
  37902. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  37903. this.startPositionFunction(worldMatrix, particle.position, particle);
  37904. var step = randomNumber(0, 1.0);
  37905. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  37906. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  37907. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  37908. }
  37909. };
  37910. ParticleSystem.prototype._getEffect = function () {
  37911. if (this._customEffect) {
  37912. return this._customEffect;
  37913. }
  37914. ;
  37915. var defines = [];
  37916. if (this._scene.clipPlane) {
  37917. defines.push("#define CLIPPLANE");
  37918. }
  37919. // Effect
  37920. var join = defines.join("\n");
  37921. if (this._cachedDefines !== join) {
  37922. this._cachedDefines = join;
  37923. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  37924. }
  37925. return this._effect;
  37926. };
  37927. ParticleSystem.prototype.animate = function () {
  37928. if (!this._started)
  37929. return;
  37930. var effect = this._getEffect();
  37931. // Check
  37932. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  37933. return;
  37934. if (this._currentRenderId === this._scene.getRenderId()) {
  37935. return;
  37936. }
  37937. this._currentRenderId = this._scene.getRenderId();
  37938. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  37939. // determine the number of particles we need to create
  37940. var newParticles;
  37941. if (this.manualEmitCount > -1) {
  37942. newParticles = this.manualEmitCount;
  37943. this._newPartsExcess = 0;
  37944. this.manualEmitCount = 0;
  37945. }
  37946. else {
  37947. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  37948. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  37949. }
  37950. if (this._newPartsExcess > 1.0) {
  37951. newParticles += this._newPartsExcess >> 0;
  37952. this._newPartsExcess -= this._newPartsExcess >> 0;
  37953. }
  37954. this._alive = false;
  37955. if (!this._stopped) {
  37956. this._actualFrame += this._scaledUpdateSpeed;
  37957. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  37958. this.stop();
  37959. }
  37960. else {
  37961. newParticles = 0;
  37962. }
  37963. this._update(newParticles);
  37964. // Stopped?
  37965. if (this._stopped) {
  37966. if (!this._alive) {
  37967. this._started = false;
  37968. if (this.disposeOnStop) {
  37969. this._scene._toBeDisposed.push(this);
  37970. }
  37971. }
  37972. }
  37973. // Update VBO
  37974. var offset = 0;
  37975. for (var index = 0; index < this.particles.length; index++) {
  37976. var particle = this.particles[index];
  37977. this._appendParticleVertex(offset++, particle, 0, 0);
  37978. this._appendParticleVertex(offset++, particle, 1, 0);
  37979. this._appendParticleVertex(offset++, particle, 1, 1);
  37980. this._appendParticleVertex(offset++, particle, 0, 1);
  37981. }
  37982. this._vertexBuffer.update(this._vertexData);
  37983. };
  37984. ParticleSystem.prototype.render = function () {
  37985. var effect = this._getEffect();
  37986. // Check
  37987. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  37988. return 0;
  37989. var engine = this._scene.getEngine();
  37990. // Render
  37991. engine.enableEffect(effect);
  37992. engine.setState(false);
  37993. var viewMatrix = this._scene.getViewMatrix();
  37994. effect.setTexture("diffuseSampler", this.particleTexture);
  37995. effect.setMatrix("view", viewMatrix);
  37996. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  37997. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  37998. if (this._scene.clipPlane) {
  37999. var clipPlane = this._scene.clipPlane;
  38000. var invView = viewMatrix.clone();
  38001. invView.invert();
  38002. effect.setMatrix("invView", invView);
  38003. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38004. }
  38005. // VBOs
  38006. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38007. // Draw order
  38008. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  38009. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38010. }
  38011. else {
  38012. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  38013. }
  38014. if (this.forceDepthWrite) {
  38015. engine.setDepthWrite(true);
  38016. }
  38017. engine.draw(true, 0, this.particles.length * 6);
  38018. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38019. return this.particles.length;
  38020. };
  38021. ParticleSystem.prototype.dispose = function () {
  38022. if (this._vertexBuffer) {
  38023. this._vertexBuffer.dispose();
  38024. this._vertexBuffer = null;
  38025. }
  38026. if (this._indexBuffer) {
  38027. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38028. this._indexBuffer = null;
  38029. }
  38030. if (this.particleTexture) {
  38031. this.particleTexture.dispose();
  38032. this.particleTexture = null;
  38033. }
  38034. // Remove from scene
  38035. var index = this._scene.particleSystems.indexOf(this);
  38036. this._scene.particleSystems.splice(index, 1);
  38037. // Callback
  38038. this.onDisposeObservable.notifyObservers(this);
  38039. this.onDisposeObservable.clear();
  38040. };
  38041. // Clone
  38042. ParticleSystem.prototype.clone = function (name, newEmitter) {
  38043. var custom = null;
  38044. var program = null;
  38045. if (this.customShader != null) {
  38046. program = this.customShader;
  38047. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38048. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38049. }
  38050. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  38051. result.customShader = program;
  38052. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  38053. if (newEmitter === undefined) {
  38054. newEmitter = this.emitter;
  38055. }
  38056. result.emitter = newEmitter;
  38057. if (this.particleTexture) {
  38058. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  38059. }
  38060. if (!this.preventAutoStart) {
  38061. result.start();
  38062. }
  38063. return result;
  38064. };
  38065. ParticleSystem.prototype.serialize = function () {
  38066. var serializationObject = {};
  38067. serializationObject.name = this.name;
  38068. serializationObject.id = this.id;
  38069. // Emitter
  38070. if (this.emitter.position) {
  38071. serializationObject.emitterId = this.emitter.id;
  38072. }
  38073. else {
  38074. serializationObject.emitter = this.emitter.asArray();
  38075. }
  38076. serializationObject.capacity = this.getCapacity();
  38077. if (this.particleTexture) {
  38078. serializationObject.textureName = this.particleTexture.name;
  38079. }
  38080. // Animations
  38081. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  38082. // Particle system
  38083. serializationObject.minAngularSpeed = this.minAngularSpeed;
  38084. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  38085. serializationObject.minSize = this.minSize;
  38086. serializationObject.maxSize = this.maxSize;
  38087. serializationObject.minEmitPower = this.minEmitPower;
  38088. serializationObject.maxEmitPower = this.maxEmitPower;
  38089. serializationObject.minLifeTime = this.minLifeTime;
  38090. serializationObject.maxLifeTime = this.maxLifeTime;
  38091. serializationObject.emitRate = this.emitRate;
  38092. serializationObject.minEmitBox = this.minEmitBox.asArray();
  38093. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  38094. serializationObject.gravity = this.gravity.asArray();
  38095. serializationObject.direction1 = this.direction1.asArray();
  38096. serializationObject.direction2 = this.direction2.asArray();
  38097. serializationObject.color1 = this.color1.asArray();
  38098. serializationObject.color2 = this.color2.asArray();
  38099. serializationObject.colorDead = this.colorDead.asArray();
  38100. serializationObject.updateSpeed = this.updateSpeed;
  38101. serializationObject.targetStopDuration = this.targetStopDuration;
  38102. serializationObject.textureMask = this.textureMask.asArray();
  38103. serializationObject.blendMode = this.blendMode;
  38104. serializationObject.customShader = this.customShader;
  38105. serializationObject.preventAutoStart = this.preventAutoStart;
  38106. return serializationObject;
  38107. };
  38108. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  38109. var name = parsedParticleSystem.name;
  38110. var custom = null;
  38111. var program = null;
  38112. if (parsedParticleSystem.customShader) {
  38113. program = parsedParticleSystem.customShader;
  38114. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  38115. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  38116. }
  38117. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  38118. particleSystem.customShader = program;
  38119. if (parsedParticleSystem.id) {
  38120. particleSystem.id = parsedParticleSystem.id;
  38121. }
  38122. // Auto start
  38123. if (parsedParticleSystem.preventAutoStart) {
  38124. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  38125. }
  38126. // Texture
  38127. if (parsedParticleSystem.textureName) {
  38128. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  38129. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  38130. }
  38131. // Emitter
  38132. if (parsedParticleSystem.emitterId) {
  38133. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  38134. }
  38135. else {
  38136. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  38137. }
  38138. // Animations
  38139. if (parsedParticleSystem.animations) {
  38140. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  38141. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  38142. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  38143. }
  38144. }
  38145. if (parsedParticleSystem.autoAnimate) {
  38146. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  38147. }
  38148. // Particle system
  38149. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  38150. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  38151. particleSystem.minSize = parsedParticleSystem.minSize;
  38152. particleSystem.maxSize = parsedParticleSystem.maxSize;
  38153. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  38154. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  38155. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  38156. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  38157. particleSystem.emitRate = parsedParticleSystem.emitRate;
  38158. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  38159. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  38160. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  38161. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  38162. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  38163. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  38164. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  38165. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  38166. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  38167. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  38168. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  38169. particleSystem.blendMode = parsedParticleSystem.blendMode;
  38170. if (!particleSystem.preventAutoStart) {
  38171. particleSystem.start();
  38172. }
  38173. return particleSystem;
  38174. };
  38175. return ParticleSystem;
  38176. }());
  38177. // Statics
  38178. ParticleSystem.BLENDMODE_ONEONE = 0;
  38179. ParticleSystem.BLENDMODE_STANDARD = 1;
  38180. BABYLON.ParticleSystem = ParticleSystem;
  38181. })(BABYLON || (BABYLON = {}));
  38182. //# sourceMappingURL=babylon.particleSystem.js.map
  38183. var BABYLON;
  38184. (function (BABYLON) {
  38185. var SolidParticle = (function () {
  38186. /**
  38187. * Creates a Solid Particle object.
  38188. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  38189. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  38190. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  38191. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  38192. * `shapeId` (integer) is the model shape identifier in the SPS.
  38193. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  38194. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  38195. */
  38196. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  38197. this.idx = 0; // particle global index
  38198. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  38199. this.position = BABYLON.Vector3.Zero(); // position
  38200. this.rotation = BABYLON.Vector3.Zero(); // rotation
  38201. this.scaling = BABYLON.Vector3.One(); // scaling
  38202. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  38203. this.velocity = BABYLON.Vector3.Zero(); // velocity
  38204. this.alive = true; // alive
  38205. this.isVisible = true; // visibility
  38206. this._pos = 0; // index of this particle in the global "positions" array
  38207. this.shapeId = 0; // model shape id
  38208. this.idxInShape = 0; // index of the particle in its shape id
  38209. this.idx = particleIndex;
  38210. this._pos = positionIndex;
  38211. this._model = model;
  38212. this.shapeId = shapeId;
  38213. this.idxInShape = idxInShape;
  38214. this._sps = sps;
  38215. if (modelBoundingInfo) {
  38216. this._modelBoundingInfo = modelBoundingInfo;
  38217. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  38218. }
  38219. }
  38220. Object.defineProperty(SolidParticle.prototype, "scale", {
  38221. /**
  38222. * legacy support, changed scale to scaling
  38223. */
  38224. get: function () {
  38225. return this.scaling;
  38226. },
  38227. set: function (scale) {
  38228. this.scaling = scale;
  38229. },
  38230. enumerable: true,
  38231. configurable: true
  38232. });
  38233. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  38234. /**
  38235. * legacy support, changed quaternion to rotationQuaternion
  38236. */
  38237. get: function () {
  38238. return this.rotationQuaternion;
  38239. },
  38240. set: function (q) {
  38241. this.rotationQuaternion = q;
  38242. },
  38243. enumerable: true,
  38244. configurable: true
  38245. });
  38246. /**
  38247. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  38248. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  38249. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  38250. */
  38251. SolidParticle.prototype.intersectsMesh = function (target) {
  38252. if (!this._boundingInfo || !target._boundingInfo) {
  38253. return false;
  38254. }
  38255. if (this._sps._bSphereOnly) {
  38256. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  38257. }
  38258. return this._boundingInfo.intersects(target._boundingInfo, false);
  38259. };
  38260. return SolidParticle;
  38261. }());
  38262. BABYLON.SolidParticle = SolidParticle;
  38263. var ModelShape = (function () {
  38264. /**
  38265. * 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.
  38266. * SPS internal tool, don't use it manually.
  38267. */
  38268. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  38269. this.shapeID = id;
  38270. this._shape = shape;
  38271. this._shapeUV = shapeUV;
  38272. this._positionFunction = posFunction;
  38273. this._vertexFunction = vtxFunction;
  38274. }
  38275. return ModelShape;
  38276. }());
  38277. BABYLON.ModelShape = ModelShape;
  38278. })(BABYLON || (BABYLON = {}));
  38279. //# sourceMappingURL=babylon.solidParticle.js.map
  38280. var BABYLON;
  38281. (function (BABYLON) {
  38282. /**
  38283. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  38284. */
  38285. var SolidParticleSystem = (function () {
  38286. /**
  38287. * Creates a SPS (Solid Particle System) object.
  38288. * `name` (String) is the SPS name, this will be the underlying mesh name.
  38289. * `scene` (Scene) is the scene in which the SPS is added.
  38290. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  38291. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  38292. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  38293. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  38294. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  38295. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  38296. */
  38297. function SolidParticleSystem(name, scene, options) {
  38298. // public members
  38299. /**
  38300. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  38301. * Example : var p = SPS.particles[i];
  38302. */
  38303. this.particles = new Array();
  38304. /**
  38305. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  38306. */
  38307. this.nbParticles = 0;
  38308. /**
  38309. * If the particles must ever face the camera (default false). Useful for planar particles.
  38310. */
  38311. this.billboard = false;
  38312. /**
  38313. * Recompute normals when adding a shape
  38314. */
  38315. this.recomputeNormals = true;
  38316. /**
  38317. * This a counter ofr your own usage. It's not set by any SPS functions.
  38318. */
  38319. this.counter = 0;
  38320. /**
  38321. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38322. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  38323. */
  38324. this.vars = {};
  38325. this._positions = new Array();
  38326. this._indices = new Array();
  38327. this._normals = new Array();
  38328. this._colors = new Array();
  38329. this._uvs = new Array();
  38330. this._index = 0; // indices index
  38331. this._updatable = true;
  38332. this._pickable = false;
  38333. this._isVisibilityBoxLocked = false;
  38334. this._alwaysVisible = false;
  38335. this._shapeCounter = 0;
  38336. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  38337. this._color = new BABYLON.Color4(0, 0, 0, 0);
  38338. this._computeParticleColor = true;
  38339. this._computeParticleTexture = true;
  38340. this._computeParticleRotation = true;
  38341. this._computeParticleVertex = false;
  38342. this._computeBoundingBox = false;
  38343. this._cam_axisZ = BABYLON.Vector3.Zero();
  38344. this._cam_axisY = BABYLON.Vector3.Zero();
  38345. this._cam_axisX = BABYLON.Vector3.Zero();
  38346. this._axisX = BABYLON.Axis.X;
  38347. this._axisY = BABYLON.Axis.Y;
  38348. this._axisZ = BABYLON.Axis.Z;
  38349. this._camDir = BABYLON.Vector3.Zero();
  38350. this._rotMatrix = new BABYLON.Matrix();
  38351. this._invertMatrix = new BABYLON.Matrix();
  38352. this._rotated = BABYLON.Vector3.Zero();
  38353. this._quaternion = new BABYLON.Quaternion();
  38354. this._vertex = BABYLON.Vector3.Zero();
  38355. this._normal = BABYLON.Vector3.Zero();
  38356. this._yaw = 0.0;
  38357. this._pitch = 0.0;
  38358. this._roll = 0.0;
  38359. this._halfroll = 0.0;
  38360. this._halfpitch = 0.0;
  38361. this._halfyaw = 0.0;
  38362. this._sinRoll = 0.0;
  38363. this._cosRoll = 0.0;
  38364. this._sinPitch = 0.0;
  38365. this._cosPitch = 0.0;
  38366. this._sinYaw = 0.0;
  38367. this._cosYaw = 0.0;
  38368. this._w = 0.0;
  38369. this._mustUnrotateFixedNormals = false;
  38370. this._minimum = BABYLON.Tmp.Vector3[0];
  38371. this._maximum = BABYLON.Tmp.Vector3[1];
  38372. this._scale = BABYLON.Tmp.Vector3[2];
  38373. this._translation = BABYLON.Tmp.Vector3[3];
  38374. this._minBbox = BABYLON.Tmp.Vector3[4];
  38375. this._maxBbox = BABYLON.Tmp.Vector3[5];
  38376. this._particlesIntersect = false;
  38377. this._bSphereOnly = false;
  38378. this._bSphereRadiusFactor = 1.0;
  38379. this.name = name;
  38380. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38381. this._camera = scene.activeCamera;
  38382. this._pickable = options ? options.isPickable : false;
  38383. this._particlesIntersect = options ? options.particleIntersection : false;
  38384. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  38385. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  38386. if (options && options.updatable) {
  38387. this._updatable = options.updatable;
  38388. }
  38389. else {
  38390. this._updatable = true;
  38391. }
  38392. if (this._pickable) {
  38393. this.pickedParticles = [];
  38394. }
  38395. }
  38396. /**
  38397. * Builds the SPS underlying mesh. Returns a standard Mesh.
  38398. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  38399. */
  38400. SolidParticleSystem.prototype.buildMesh = function () {
  38401. if (this.nbParticles === 0) {
  38402. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  38403. this.addShape(triangle, 1);
  38404. triangle.dispose();
  38405. }
  38406. this._positions32 = new Float32Array(this._positions);
  38407. this._uvs32 = new Float32Array(this._uvs);
  38408. this._colors32 = new Float32Array(this._colors);
  38409. if (this.recomputeNormals) {
  38410. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  38411. }
  38412. this._normals32 = new Float32Array(this._normals);
  38413. this._fixedNormal32 = new Float32Array(this._normals);
  38414. if (this._mustUnrotateFixedNormals) {
  38415. this._unrotateFixedNormals();
  38416. }
  38417. var vertexData = new BABYLON.VertexData();
  38418. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  38419. vertexData.indices = this._indices;
  38420. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  38421. if (this._uvs32) {
  38422. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  38423. ;
  38424. }
  38425. if (this._colors32) {
  38426. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  38427. }
  38428. var mesh = new BABYLON.Mesh(this.name, this._scene);
  38429. vertexData.applyToMesh(mesh, this._updatable);
  38430. this.mesh = mesh;
  38431. this.mesh.isPickable = this._pickable;
  38432. // free memory
  38433. this._positions = null;
  38434. this._normals = null;
  38435. this._uvs = null;
  38436. this._colors = null;
  38437. if (!this._updatable) {
  38438. this.particles.length = 0;
  38439. }
  38440. return mesh;
  38441. };
  38442. /**
  38443. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  38444. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  38445. * Thus the particles generated from `digest()` have their property `position` set yet.
  38446. * `mesh` ( Mesh ) is the mesh to be digested
  38447. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  38448. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  38449. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  38450. */
  38451. SolidParticleSystem.prototype.digest = function (mesh, options) {
  38452. var size = (options && options.facetNb) || 1;
  38453. var number = (options && options.number);
  38454. var delta = (options && options.delta) || 0;
  38455. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38456. var meshInd = mesh.getIndices();
  38457. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38458. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38459. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38460. var f = 0; // facet counter
  38461. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  38462. // compute size from number
  38463. if (number) {
  38464. number = (number > totalFacets) ? totalFacets : number;
  38465. size = Math.round(totalFacets / number);
  38466. delta = 0;
  38467. }
  38468. else {
  38469. size = (size > totalFacets) ? totalFacets : size;
  38470. }
  38471. var facetPos = []; // submesh positions
  38472. var facetInd = []; // submesh indices
  38473. var facetUV = []; // submesh UV
  38474. var facetCol = []; // submesh colors
  38475. var barycenter = BABYLON.Tmp.Vector3[0];
  38476. var rand;
  38477. var sizeO = size;
  38478. while (f < totalFacets) {
  38479. size = sizeO + Math.floor((1 + delta) * Math.random());
  38480. if (f > totalFacets - size) {
  38481. size = totalFacets - f;
  38482. }
  38483. // reset temp arrays
  38484. facetPos.length = 0;
  38485. facetInd.length = 0;
  38486. facetUV.length = 0;
  38487. facetCol.length = 0;
  38488. // iterate over "size" facets
  38489. var fi = 0;
  38490. for (var j = f * 3; j < (f + size) * 3; j++) {
  38491. facetInd.push(fi);
  38492. var i = meshInd[j];
  38493. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  38494. if (meshUV) {
  38495. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  38496. }
  38497. if (meshCol) {
  38498. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  38499. }
  38500. fi++;
  38501. }
  38502. // create a model shape for each single particle
  38503. var idx = this.nbParticles;
  38504. var shape = this._posToShape(facetPos);
  38505. var shapeUV = this._uvsToShapeUV(facetUV);
  38506. // compute the barycenter of the shape
  38507. var v;
  38508. for (v = 0; v < shape.length; v++) {
  38509. barycenter.addInPlace(shape[v]);
  38510. }
  38511. barycenter.scaleInPlace(1 / shape.length);
  38512. // shift the shape from its barycenter to the origin
  38513. for (v = 0; v < shape.length; v++) {
  38514. shape[v].subtractInPlace(barycenter);
  38515. }
  38516. var bInfo;
  38517. if (this._particlesIntersect) {
  38518. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  38519. }
  38520. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  38521. // add the particle in the SPS
  38522. var currentPos = this._positions.length;
  38523. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  38524. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  38525. // initialize the particle position
  38526. this.particles[this.nbParticles].position.addInPlace(barycenter);
  38527. this._index += shape.length;
  38528. idx++;
  38529. this.nbParticles++;
  38530. this._shapeCounter++;
  38531. f += size;
  38532. }
  38533. return this;
  38534. };
  38535. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  38536. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  38537. var index = 0;
  38538. var idx = 0;
  38539. for (var p = 0; p < this.particles.length; p++) {
  38540. this._particle = this.particles[p];
  38541. this._shape = this._particle._model._shape;
  38542. if (this._particle.rotationQuaternion) {
  38543. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38544. }
  38545. else {
  38546. this._yaw = this._particle.rotation.y;
  38547. this._pitch = this._particle.rotation.x;
  38548. this._roll = this._particle.rotation.z;
  38549. this._quaternionRotationYPR();
  38550. }
  38551. this._quaternionToRotationMatrix();
  38552. this._rotMatrix.invertToRef(this._invertMatrix);
  38553. for (var pt = 0; pt < this._shape.length; pt++) {
  38554. idx = index + pt * 3;
  38555. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  38556. this._fixedNormal32[idx] = this._normal.x;
  38557. this._fixedNormal32[idx + 1] = this._normal.y;
  38558. this._fixedNormal32[idx + 2] = this._normal.z;
  38559. }
  38560. index = idx + 3;
  38561. }
  38562. };
  38563. //reset copy
  38564. SolidParticleSystem.prototype._resetCopy = function () {
  38565. this._copy.position.x = 0;
  38566. this._copy.position.y = 0;
  38567. this._copy.position.z = 0;
  38568. this._copy.rotation.x = 0;
  38569. this._copy.rotation.y = 0;
  38570. this._copy.rotation.z = 0;
  38571. this._copy.rotationQuaternion = null;
  38572. this._copy.scaling.x = 1;
  38573. this._copy.scaling.y = 1;
  38574. this._copy.scaling.z = 1;
  38575. this._copy.uvs.x = 0;
  38576. this._copy.uvs.y = 0;
  38577. this._copy.uvs.z = 1;
  38578. this._copy.uvs.w = 1;
  38579. this._copy.color = null;
  38580. };
  38581. // _meshBuilder : inserts the shape model in the global SPS mesh
  38582. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  38583. var i;
  38584. var u = 0;
  38585. var c = 0;
  38586. var n = 0;
  38587. this._resetCopy();
  38588. if (options && options.positionFunction) {
  38589. options.positionFunction(this._copy, idx, idxInShape);
  38590. this._mustUnrotateFixedNormals = true;
  38591. }
  38592. if (this._copy.rotationQuaternion) {
  38593. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38594. }
  38595. else {
  38596. this._yaw = this._copy.rotation.y;
  38597. this._pitch = this._copy.rotation.x;
  38598. this._roll = this._copy.rotation.z;
  38599. this._quaternionRotationYPR();
  38600. }
  38601. this._quaternionToRotationMatrix();
  38602. for (i = 0; i < shape.length; i++) {
  38603. this._vertex.x = shape[i].x;
  38604. this._vertex.y = shape[i].y;
  38605. this._vertex.z = shape[i].z;
  38606. if (options && options.vertexFunction) {
  38607. options.vertexFunction(this._copy, this._vertex, i);
  38608. }
  38609. this._vertex.x *= this._copy.scaling.x;
  38610. this._vertex.y *= this._copy.scaling.y;
  38611. this._vertex.z *= this._copy.scaling.z;
  38612. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38613. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  38614. if (meshUV) {
  38615. 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);
  38616. u += 2;
  38617. }
  38618. if (this._copy.color) {
  38619. this._color = this._copy.color;
  38620. }
  38621. else if (meshCol && meshCol[c] !== undefined) {
  38622. this._color.r = meshCol[c];
  38623. this._color.g = meshCol[c + 1];
  38624. this._color.b = meshCol[c + 2];
  38625. this._color.a = meshCol[c + 3];
  38626. }
  38627. else {
  38628. this._color.r = 1;
  38629. this._color.g = 1;
  38630. this._color.b = 1;
  38631. this._color.a = 1;
  38632. }
  38633. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  38634. c += 4;
  38635. if (!this.recomputeNormals && meshNor) {
  38636. this._normal.x = meshNor[n];
  38637. this._normal.y = meshNor[n + 1];
  38638. this._normal.z = meshNor[n + 2];
  38639. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  38640. normals.push(this._normal.x, this._normal.y, this._normal.z);
  38641. n += 3;
  38642. }
  38643. }
  38644. for (i = 0; i < meshInd.length; i++) {
  38645. indices.push(p + meshInd[i]);
  38646. }
  38647. if (this._pickable) {
  38648. var nbfaces = meshInd.length / 3;
  38649. for (i = 0; i < nbfaces; i++) {
  38650. this.pickedParticles.push({ idx: idx, faceId: i });
  38651. }
  38652. }
  38653. return this._copy;
  38654. };
  38655. // returns a shape array from positions array
  38656. SolidParticleSystem.prototype._posToShape = function (positions) {
  38657. var shape = [];
  38658. for (var i = 0; i < positions.length; i += 3) {
  38659. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  38660. }
  38661. return shape;
  38662. };
  38663. // returns a shapeUV array from a Vector4 uvs
  38664. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  38665. var shapeUV = [];
  38666. if (uvs) {
  38667. for (var i = 0; i < uvs.length; i++)
  38668. shapeUV.push(uvs[i]);
  38669. }
  38670. return shapeUV;
  38671. };
  38672. // adds a new particle object in the particles array
  38673. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  38674. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  38675. this.particles.push(sp);
  38676. return sp;
  38677. };
  38678. /**
  38679. * Adds some particles to the SPS from the model shape. Returns the shape id.
  38680. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  38681. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  38682. * `nb` (positive integer) the number of particles to be created from this model
  38683. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  38684. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  38685. */
  38686. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  38687. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38688. var meshInd = mesh.getIndices();
  38689. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38690. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38691. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38692. var bbInfo;
  38693. if (this._particlesIntersect) {
  38694. bbInfo = mesh.getBoundingInfo();
  38695. }
  38696. var shape = this._posToShape(meshPos);
  38697. var shapeUV = this._uvsToShapeUV(meshUV);
  38698. var posfunc = options ? options.positionFunction : null;
  38699. var vtxfunc = options ? options.vertexFunction : null;
  38700. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  38701. // particles
  38702. var sp;
  38703. var currentCopy;
  38704. var idx = this.nbParticles;
  38705. for (var i = 0; i < nb; i++) {
  38706. var currentPos = this._positions.length;
  38707. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  38708. if (this._updatable) {
  38709. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  38710. sp.position.copyFrom(currentCopy.position);
  38711. sp.rotation.copyFrom(currentCopy.rotation);
  38712. if (currentCopy.rotationQuaternion) {
  38713. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  38714. }
  38715. if (currentCopy.color) {
  38716. sp.color.copyFrom(currentCopy.color);
  38717. }
  38718. sp.scaling.copyFrom(currentCopy.scaling);
  38719. sp.uvs.copyFrom(currentCopy.uvs);
  38720. }
  38721. this._index += shape.length;
  38722. idx++;
  38723. }
  38724. this.nbParticles += nb;
  38725. this._shapeCounter++;
  38726. return this._shapeCounter - 1;
  38727. };
  38728. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  38729. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  38730. this._resetCopy();
  38731. if (particle._model._positionFunction) {
  38732. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  38733. }
  38734. if (this._copy.rotationQuaternion) {
  38735. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  38736. }
  38737. else {
  38738. this._yaw = this._copy.rotation.y;
  38739. this._pitch = this._copy.rotation.x;
  38740. this._roll = this._copy.rotation.z;
  38741. this._quaternionRotationYPR();
  38742. }
  38743. this._quaternionToRotationMatrix();
  38744. this._shape = particle._model._shape;
  38745. for (var pt = 0; pt < this._shape.length; pt++) {
  38746. this._vertex.x = this._shape[pt].x;
  38747. this._vertex.y = this._shape[pt].y;
  38748. this._vertex.z = this._shape[pt].z;
  38749. if (particle._model._vertexFunction) {
  38750. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  38751. }
  38752. this._vertex.x *= this._copy.scaling.x;
  38753. this._vertex.y *= this._copy.scaling.y;
  38754. this._vertex.z *= this._copy.scaling.z;
  38755. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  38756. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  38757. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  38758. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  38759. }
  38760. particle.position.x = 0.0;
  38761. particle.position.y = 0.0;
  38762. particle.position.z = 0.0;
  38763. particle.rotation.x = 0.0;
  38764. particle.rotation.y = 0.0;
  38765. particle.rotation.z = 0.0;
  38766. particle.rotationQuaternion = null;
  38767. particle.scaling.x = 1.0;
  38768. particle.scaling.y = 1.0;
  38769. particle.scaling.z = 1.0;
  38770. };
  38771. /**
  38772. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  38773. * Returns the SPS.
  38774. */
  38775. SolidParticleSystem.prototype.rebuildMesh = function () {
  38776. for (var p = 0; p < this.particles.length; p++) {
  38777. this._rebuildParticle(this.particles[p]);
  38778. }
  38779. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  38780. return this;
  38781. };
  38782. /**
  38783. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  38784. * This method calls `updateParticle()` for each particle of the SPS.
  38785. * For an animated SPS, it is usually called within the render loop.
  38786. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  38787. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  38788. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  38789. * Returns the SPS.
  38790. */
  38791. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  38792. if (start === void 0) { start = 0; }
  38793. if (end === void 0) { end = this.nbParticles - 1; }
  38794. if (update === void 0) { update = true; }
  38795. if (!this._updatable) {
  38796. return;
  38797. }
  38798. // custom beforeUpdate
  38799. this.beforeUpdateParticles(start, end, update);
  38800. this._cam_axisX.x = 1.0;
  38801. this._cam_axisX.y = 0.0;
  38802. this._cam_axisX.z = 0.0;
  38803. this._cam_axisY.x = 0.0;
  38804. this._cam_axisY.y = 1.0;
  38805. this._cam_axisY.z = 0.0;
  38806. this._cam_axisZ.x = 0.0;
  38807. this._cam_axisZ.y = 0.0;
  38808. this._cam_axisZ.z = 1.0;
  38809. // if the particles will always face the camera
  38810. if (this.billboard) {
  38811. this.mesh.computeWorldMatrix(true);
  38812. // compute the camera position and un-rotate it by the current mesh rotation
  38813. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  38814. this._quaternionToRotationMatrix();
  38815. this._rotMatrix.invertToRef(this._invertMatrix);
  38816. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  38817. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  38818. this._cam_axisZ.normalize();
  38819. // same for camera up vector extracted from the cam view matrix
  38820. var view = this._camera.getViewMatrix(true);
  38821. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  38822. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  38823. this._cam_axisY.normalize();
  38824. this._cam_axisX.normalize();
  38825. }
  38826. }
  38827. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  38828. var idx = 0; // current position index in the global array positions32
  38829. var index = 0; // position start index in the global array positions32 of the current particle
  38830. var colidx = 0; // current color index in the global array colors32
  38831. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  38832. var uvidx = 0; // current uv index in the global array uvs32
  38833. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  38834. var pt = 0; // current index in the particle model shape
  38835. if (this.mesh.isFacetDataEnabled) {
  38836. this._computeBoundingBox = true;
  38837. }
  38838. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  38839. if (this._computeBoundingBox) {
  38840. if (start == 0 && end == this.nbParticles - 1) {
  38841. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  38842. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  38843. }
  38844. else {
  38845. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  38846. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  38847. }
  38848. }
  38849. // particle loop
  38850. index = this.particles[start]._pos;
  38851. var vpos = (index / 3) | 0;
  38852. colorIndex = vpos * 4;
  38853. uvIndex = vpos * 2;
  38854. for (var p = start; p <= end; p++) {
  38855. this._particle = this.particles[p];
  38856. this._shape = this._particle._model._shape;
  38857. this._shapeUV = this._particle._model._shapeUV;
  38858. // call to custom user function to update the particle properties
  38859. this.updateParticle(this._particle);
  38860. if (this._particle.isVisible) {
  38861. // particle rotation matrix
  38862. if (this.billboard) {
  38863. this._particle.rotation.x = 0.0;
  38864. this._particle.rotation.y = 0.0;
  38865. }
  38866. if (this._computeParticleRotation || this.billboard) {
  38867. if (this._particle.rotationQuaternion) {
  38868. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  38869. }
  38870. else {
  38871. this._yaw = this._particle.rotation.y;
  38872. this._pitch = this._particle.rotation.x;
  38873. this._roll = this._particle.rotation.z;
  38874. this._quaternionRotationYPR();
  38875. }
  38876. this._quaternionToRotationMatrix();
  38877. }
  38878. // particle vertex loop
  38879. for (pt = 0; pt < this._shape.length; pt++) {
  38880. idx = index + pt * 3;
  38881. colidx = colorIndex + pt * 4;
  38882. uvidx = uvIndex + pt * 2;
  38883. this._vertex.x = this._shape[pt].x;
  38884. this._vertex.y = this._shape[pt].y;
  38885. this._vertex.z = this._shape[pt].z;
  38886. if (this._computeParticleVertex) {
  38887. this.updateParticleVertex(this._particle, this._vertex, pt);
  38888. }
  38889. // positions
  38890. this._vertex.x *= this._particle.scaling.x;
  38891. this._vertex.y *= this._particle.scaling.y;
  38892. this._vertex.z *= this._particle.scaling.z;
  38893. 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];
  38894. 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;
  38895. 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;
  38896. 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;
  38897. 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;
  38898. 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;
  38899. 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;
  38900. if (this._computeBoundingBox) {
  38901. if (this._positions32[idx] < this._minimum.x) {
  38902. this._minimum.x = this._positions32[idx];
  38903. }
  38904. if (this._positions32[idx] > this._maximum.x) {
  38905. this._maximum.x = this._positions32[idx];
  38906. }
  38907. if (this._positions32[idx + 1] < this._minimum.y) {
  38908. this._minimum.y = this._positions32[idx + 1];
  38909. }
  38910. if (this._positions32[idx + 1] > this._maximum.y) {
  38911. this._maximum.y = this._positions32[idx + 1];
  38912. }
  38913. if (this._positions32[idx + 2] < this._minimum.z) {
  38914. this._minimum.z = this._positions32[idx + 2];
  38915. }
  38916. if (this._positions32[idx + 2] > this._maximum.z) {
  38917. this._maximum.z = this._positions32[idx + 2];
  38918. }
  38919. }
  38920. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  38921. if (!this._computeParticleVertex) {
  38922. this._normal.x = this._fixedNormal32[idx];
  38923. this._normal.y = this._fixedNormal32[idx + 1];
  38924. this._normal.z = this._fixedNormal32[idx + 2];
  38925. 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]);
  38926. 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]);
  38927. 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]);
  38928. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  38929. 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;
  38930. 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;
  38931. }
  38932. if (this._computeParticleColor) {
  38933. this._colors32[colidx] = this._particle.color.r;
  38934. this._colors32[colidx + 1] = this._particle.color.g;
  38935. this._colors32[colidx + 2] = this._particle.color.b;
  38936. this._colors32[colidx + 3] = this._particle.color.a;
  38937. }
  38938. if (this._computeParticleTexture) {
  38939. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38940. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38941. }
  38942. }
  38943. }
  38944. else {
  38945. for (pt = 0; pt < this._shape.length; pt++) {
  38946. idx = index + pt * 3;
  38947. colidx = colorIndex + pt * 4;
  38948. uvidx = uvIndex + pt * 2;
  38949. this._positions32[idx] = this._camera.position.x;
  38950. this._positions32[idx + 1] = this._camera.position.y;
  38951. this._positions32[idx + 2] = this._camera.position.z;
  38952. this._normals32[idx] = 0.0;
  38953. this._normals32[idx + 1] = 0.0;
  38954. this._normals32[idx + 2] = 0.0;
  38955. if (this._computeParticleColor) {
  38956. this._colors32[colidx] = this._particle.color.r;
  38957. this._colors32[colidx + 1] = this._particle.color.g;
  38958. this._colors32[colidx + 2] = this._particle.color.b;
  38959. this._colors32[colidx + 3] = this._particle.color.a;
  38960. }
  38961. if (this._computeParticleTexture) {
  38962. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  38963. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  38964. }
  38965. }
  38966. }
  38967. // if the particle intersections must be computed : update the bbInfo
  38968. if (this._particlesIntersect) {
  38969. var bInfo = this._particle._boundingInfo;
  38970. var bBox = bInfo.boundingBox;
  38971. var bSphere = bInfo.boundingSphere;
  38972. if (!this._bSphereOnly) {
  38973. // place, scale and rotate the particle bbox within the SPS local system, then update it
  38974. for (var b = 0; b < bBox.vectors.length; b++) {
  38975. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  38976. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  38977. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  38978. 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];
  38979. 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;
  38980. 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;
  38981. 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;
  38982. 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;
  38983. 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;
  38984. 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;
  38985. }
  38986. bBox._update(this.mesh._worldMatrix);
  38987. }
  38988. // place and scale the particle bouding sphere in the SPS local system, then update it
  38989. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  38990. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  38991. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  38992. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  38993. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  38994. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  38995. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  38996. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  38997. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  38998. 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));
  38999. bSphere._update(this.mesh._worldMatrix);
  39000. }
  39001. // increment indexes for the next particle
  39002. index = idx + 3;
  39003. colorIndex = colidx + 4;
  39004. uvIndex = uvidx + 2;
  39005. }
  39006. // if the VBO must be updated
  39007. if (update) {
  39008. if (this._computeParticleColor) {
  39009. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  39010. }
  39011. if (this._computeParticleTexture) {
  39012. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  39013. }
  39014. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  39015. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  39016. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  39017. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  39018. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  39019. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  39020. for (var i = 0; i < this._normals32.length; i++) {
  39021. this._fixedNormal32[i] = this._normals32[i];
  39022. }
  39023. }
  39024. if (!this.mesh.areNormalsFrozen) {
  39025. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  39026. }
  39027. }
  39028. }
  39029. if (this._computeBoundingBox) {
  39030. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  39031. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  39032. }
  39033. this.afterUpdateParticles(start, end, update);
  39034. return this;
  39035. };
  39036. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  39037. this._halfroll = this._roll * 0.5;
  39038. this._halfpitch = this._pitch * 0.5;
  39039. this._halfyaw = this._yaw * 0.5;
  39040. this._sinRoll = Math.sin(this._halfroll);
  39041. this._cosRoll = Math.cos(this._halfroll);
  39042. this._sinPitch = Math.sin(this._halfpitch);
  39043. this._cosPitch = Math.cos(this._halfpitch);
  39044. this._sinYaw = Math.sin(this._halfyaw);
  39045. this._cosYaw = Math.cos(this._halfyaw);
  39046. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  39047. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  39048. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  39049. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  39050. };
  39051. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  39052. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  39053. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  39054. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  39055. this._rotMatrix.m[3] = 0;
  39056. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  39057. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  39058. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  39059. this._rotMatrix.m[7] = 0;
  39060. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  39061. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  39062. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  39063. this._rotMatrix.m[11] = 0;
  39064. this._rotMatrix.m[12] = 0;
  39065. this._rotMatrix.m[13] = 0;
  39066. this._rotMatrix.m[14] = 0;
  39067. this._rotMatrix.m[15] = 1.0;
  39068. };
  39069. /**
  39070. * Disposes the SPS.
  39071. * Returns nothing.
  39072. */
  39073. SolidParticleSystem.prototype.dispose = function () {
  39074. this.mesh.dispose();
  39075. this.vars = null;
  39076. // drop references to internal big arrays for the GC
  39077. this._positions = null;
  39078. this._indices = null;
  39079. this._normals = null;
  39080. this._uvs = null;
  39081. this._colors = null;
  39082. this._positions32 = null;
  39083. this._normals32 = null;
  39084. this._fixedNormal32 = null;
  39085. this._uvs32 = null;
  39086. this._colors32 = null;
  39087. this.pickedParticles = null;
  39088. };
  39089. /**
  39090. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  39091. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39092. * Returns the SPS.
  39093. */
  39094. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  39095. if (!this._isVisibilityBoxLocked) {
  39096. this.mesh.refreshBoundingInfo();
  39097. }
  39098. return this;
  39099. };
  39100. /**
  39101. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  39102. * @param size the size (float) of the visibility box
  39103. * note : this doesn't lock the SPS mesh bounding box.
  39104. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39105. */
  39106. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  39107. var vis = size / 2;
  39108. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  39109. };
  39110. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  39111. // getter and setter
  39112. get: function () {
  39113. return this._alwaysVisible;
  39114. },
  39115. /**
  39116. * Sets the SPS as always visible or not
  39117. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39118. */
  39119. set: function (val) {
  39120. this._alwaysVisible = val;
  39121. this.mesh.alwaysSelectAsActiveMesh = val;
  39122. },
  39123. enumerable: true,
  39124. configurable: true
  39125. });
  39126. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  39127. get: function () {
  39128. return this._isVisibilityBoxLocked;
  39129. },
  39130. /**
  39131. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  39132. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  39133. */
  39134. set: function (val) {
  39135. this._isVisibilityBoxLocked = val;
  39136. this.mesh.getBoundingInfo().isLocked = val;
  39137. },
  39138. enumerable: true,
  39139. configurable: true
  39140. });
  39141. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  39142. // getters
  39143. get: function () {
  39144. return this._computeParticleRotation;
  39145. },
  39146. // Optimizer setters
  39147. /**
  39148. * Tells to `setParticles()` to compute the particle rotations or not.
  39149. * Default value : true. The SPS is faster when it's set to false.
  39150. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  39151. */
  39152. set: function (val) {
  39153. this._computeParticleRotation = val;
  39154. },
  39155. enumerable: true,
  39156. configurable: true
  39157. });
  39158. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  39159. get: function () {
  39160. return this._computeParticleColor;
  39161. },
  39162. /**
  39163. * Tells to `setParticles()` to compute the particle colors or not.
  39164. * Default value : true. The SPS is faster when it's set to false.
  39165. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  39166. */
  39167. set: function (val) {
  39168. this._computeParticleColor = val;
  39169. },
  39170. enumerable: true,
  39171. configurable: true
  39172. });
  39173. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  39174. get: function () {
  39175. return this._computeParticleTexture;
  39176. },
  39177. /**
  39178. * Tells to `setParticles()` to compute the particle textures or not.
  39179. * Default value : true. The SPS is faster when it's set to false.
  39180. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  39181. */
  39182. set: function (val) {
  39183. this._computeParticleTexture = val;
  39184. },
  39185. enumerable: true,
  39186. configurable: true
  39187. });
  39188. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  39189. get: function () {
  39190. return this._computeParticleVertex;
  39191. },
  39192. /**
  39193. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  39194. * Default value : false. The SPS is faster when it's set to false.
  39195. * Note : the particle custom vertex positions aren't stored values.
  39196. */
  39197. set: function (val) {
  39198. this._computeParticleVertex = val;
  39199. },
  39200. enumerable: true,
  39201. configurable: true
  39202. });
  39203. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  39204. get: function () {
  39205. return this._computeBoundingBox;
  39206. },
  39207. /**
  39208. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  39209. */
  39210. set: function (val) {
  39211. this._computeBoundingBox = val;
  39212. },
  39213. enumerable: true,
  39214. configurable: true
  39215. });
  39216. // =======================================================================
  39217. // Particle behavior logic
  39218. // these following methods may be overwritten by the user to fit his needs
  39219. /**
  39220. * This function does nothing. It may be overwritten to set all the particle first values.
  39221. * The SPS doesn't call this function, you may have to call it by your own.
  39222. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39223. */
  39224. SolidParticleSystem.prototype.initParticles = function () {
  39225. };
  39226. /**
  39227. * This function does nothing. It may be overwritten to recycle a particle.
  39228. * The SPS doesn't call this function, you may have to call it by your own.
  39229. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39230. */
  39231. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  39232. return particle;
  39233. };
  39234. /**
  39235. * Updates a particle : this function should be overwritten by the user.
  39236. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  39237. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  39238. * ex : just set a particle position or velocity and recycle conditions
  39239. */
  39240. SolidParticleSystem.prototype.updateParticle = function (particle) {
  39241. return particle;
  39242. };
  39243. /**
  39244. * Updates a vertex of a particle : it can be overwritten by the user.
  39245. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  39246. * @param particle the current particle
  39247. * @param vertex the current index of the current particle
  39248. * @param pt the index of the current vertex in the particle shape
  39249. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  39250. * ex : just set a vertex particle position
  39251. */
  39252. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  39253. return vertex;
  39254. };
  39255. /**
  39256. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  39257. * This does nothing and may be overwritten by the user.
  39258. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39259. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39260. * @param update the boolean update value actually passed to setParticles()
  39261. */
  39262. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  39263. };
  39264. /**
  39265. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  39266. * This will be passed three parameters.
  39267. * This does nothing and may be overwritten by the user.
  39268. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39269. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  39270. * @param update the boolean update value actually passed to setParticles()
  39271. */
  39272. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  39273. };
  39274. return SolidParticleSystem;
  39275. }());
  39276. BABYLON.SolidParticleSystem = SolidParticleSystem;
  39277. })(BABYLON || (BABYLON = {}));
  39278. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  39279. /// <reference path="babylon.mesh.ts" />
  39280. var BABYLON;
  39281. (function (BABYLON) {
  39282. var GroundMesh = (function (_super) {
  39283. __extends(GroundMesh, _super);
  39284. function GroundMesh(name, scene) {
  39285. var _this = _super.call(this, name, scene) || this;
  39286. _this.generateOctree = false;
  39287. _this._worldInverse = new BABYLON.Matrix();
  39288. return _this;
  39289. }
  39290. GroundMesh.prototype.getClassName = function () {
  39291. return "GroundMesh";
  39292. };
  39293. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39294. get: function () {
  39295. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39296. },
  39297. enumerable: true,
  39298. configurable: true
  39299. });
  39300. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39301. get: function () {
  39302. return this._subdivisionsX;
  39303. },
  39304. enumerable: true,
  39305. configurable: true
  39306. });
  39307. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39308. get: function () {
  39309. return this._subdivisionsY;
  39310. },
  39311. enumerable: true,
  39312. configurable: true
  39313. });
  39314. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39315. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39316. this._subdivisionsX = chunksCount;
  39317. this._subdivisionsY = chunksCount;
  39318. this.subdivide(chunksCount);
  39319. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39320. };
  39321. /**
  39322. * Returns a height (y) value in the Worl system :
  39323. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39324. * Returns the ground y position if (x, z) are outside the ground surface.
  39325. */
  39326. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39327. var world = this.getWorldMatrix();
  39328. var invMat = BABYLON.Tmp.Matrix[5];
  39329. world.invertToRef(invMat);
  39330. var tmpVect = BABYLON.Tmp.Vector3[8];
  39331. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39332. x = tmpVect.x;
  39333. z = tmpVect.z;
  39334. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39335. return this.position.y;
  39336. }
  39337. if (!this._heightQuads || this._heightQuads.length == 0) {
  39338. this._initHeightQuads();
  39339. this._computeHeightQuads();
  39340. }
  39341. var facet = this._getFacetAt(x, z);
  39342. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39343. // return y in the World system
  39344. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39345. return tmpVect.y;
  39346. };
  39347. /**
  39348. * Returns a normalized vector (Vector3) orthogonal to the ground
  39349. * at the ground coordinates (x, z) expressed in the World system.
  39350. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39351. */
  39352. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39353. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39354. this.getNormalAtCoordinatesToRef(x, z, normal);
  39355. return normal;
  39356. };
  39357. /**
  39358. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39359. * at the ground coordinates (x, z) expressed in the World system.
  39360. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39361. * Returns the GroundMesh.
  39362. */
  39363. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39364. var world = this.getWorldMatrix();
  39365. var tmpMat = BABYLON.Tmp.Matrix[5];
  39366. world.invertToRef(tmpMat);
  39367. var tmpVect = BABYLON.Tmp.Vector3[8];
  39368. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39369. x = tmpVect.x;
  39370. z = tmpVect.z;
  39371. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39372. return this;
  39373. }
  39374. if (!this._heightQuads || this._heightQuads.length == 0) {
  39375. this._initHeightQuads();
  39376. this._computeHeightQuads();
  39377. }
  39378. var facet = this._getFacetAt(x, z);
  39379. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39380. return this;
  39381. };
  39382. /**
  39383. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39384. * if the ground has been updated.
  39385. * This can be used in the render loop.
  39386. * Returns the GroundMesh.
  39387. */
  39388. GroundMesh.prototype.updateCoordinateHeights = function () {
  39389. if (!this._heightQuads || this._heightQuads.length == 0) {
  39390. this._initHeightQuads();
  39391. }
  39392. this._computeHeightQuads();
  39393. return this;
  39394. };
  39395. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39396. GroundMesh.prototype._getFacetAt = function (x, z) {
  39397. // retrieve col and row from x, z coordinates in the ground local system
  39398. var subdivisionsX = this._subdivisionsX;
  39399. var subdivisionsY = this._subdivisionsY;
  39400. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39401. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39402. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39403. var facet;
  39404. if (z < quad.slope.x * x + quad.slope.y) {
  39405. facet = quad.facet1;
  39406. }
  39407. else {
  39408. facet = quad.facet2;
  39409. }
  39410. return facet;
  39411. };
  39412. // Creates and populates the heightMap array with "facet" elements :
  39413. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39414. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39415. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39416. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39417. // Returns the GroundMesh.
  39418. GroundMesh.prototype._initHeightQuads = function () {
  39419. var subdivisionsX = this._subdivisionsX;
  39420. var subdivisionsY = this._subdivisionsY;
  39421. this._heightQuads = new Array();
  39422. for (var row = 0; row < subdivisionsY; row++) {
  39423. for (var col = 0; col < subdivisionsX; col++) {
  39424. 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) };
  39425. this._heightQuads[row * subdivisionsX + col] = quad;
  39426. }
  39427. }
  39428. return this;
  39429. };
  39430. // Compute each quad element values and update the the heightMap array :
  39431. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39432. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39433. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39434. // Returns the GroundMesh.
  39435. GroundMesh.prototype._computeHeightQuads = function () {
  39436. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39437. var v1 = BABYLON.Tmp.Vector3[3];
  39438. var v2 = BABYLON.Tmp.Vector3[2];
  39439. var v3 = BABYLON.Tmp.Vector3[1];
  39440. var v4 = BABYLON.Tmp.Vector3[0];
  39441. var v1v2 = BABYLON.Tmp.Vector3[4];
  39442. var v1v3 = BABYLON.Tmp.Vector3[5];
  39443. var v1v4 = BABYLON.Tmp.Vector3[6];
  39444. var norm1 = BABYLON.Tmp.Vector3[7];
  39445. var norm2 = BABYLON.Tmp.Vector3[8];
  39446. var i = 0;
  39447. var j = 0;
  39448. var k = 0;
  39449. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39450. var h = 0;
  39451. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39452. var d2 = 0;
  39453. var subdivisionsX = this._subdivisionsX;
  39454. var subdivisionsY = this._subdivisionsY;
  39455. for (var row = 0; row < subdivisionsY; row++) {
  39456. for (var col = 0; col < subdivisionsX; col++) {
  39457. i = col * 3;
  39458. j = row * (subdivisionsX + 1) * 3;
  39459. k = (row + 1) * (subdivisionsX + 1) * 3;
  39460. v1.x = positions[j + i];
  39461. v1.y = positions[j + i + 1];
  39462. v1.z = positions[j + i + 2];
  39463. v2.x = positions[j + i + 3];
  39464. v2.y = positions[j + i + 4];
  39465. v2.z = positions[j + i + 5];
  39466. v3.x = positions[k + i];
  39467. v3.y = positions[k + i + 1];
  39468. v3.z = positions[k + i + 2];
  39469. v4.x = positions[k + i + 3];
  39470. v4.y = positions[k + i + 4];
  39471. v4.z = positions[k + i + 5];
  39472. // 2D slope V1V4
  39473. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39474. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39475. // facet equations :
  39476. // we compute each facet normal vector
  39477. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39478. // we compute the value d by applying the equation to v1 which belongs to the plane
  39479. // then we store the facet equation in a Vector4
  39480. v2.subtractToRef(v1, v1v2);
  39481. v3.subtractToRef(v1, v1v3);
  39482. v4.subtractToRef(v1, v1v4);
  39483. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39484. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39485. norm1.normalize();
  39486. norm2.normalize();
  39487. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39488. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39489. var quad = this._heightQuads[row * subdivisionsX + col];
  39490. quad.slope.copyFromFloats(cd, h);
  39491. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39492. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39493. }
  39494. }
  39495. return this;
  39496. };
  39497. GroundMesh.prototype.serialize = function (serializationObject) {
  39498. _super.prototype.serialize.call(this, serializationObject);
  39499. serializationObject.subdivisionsX = this._subdivisionsX;
  39500. serializationObject.subdivisionsY = this._subdivisionsY;
  39501. serializationObject.minX = this._minX;
  39502. serializationObject.maxX = this._maxX;
  39503. serializationObject.minZ = this._minZ;
  39504. serializationObject.maxZ = this._maxZ;
  39505. serializationObject.width = this._width;
  39506. serializationObject.height = this._height;
  39507. };
  39508. GroundMesh.Parse = function (parsedMesh, scene) {
  39509. var result = new GroundMesh(parsedMesh.name, scene);
  39510. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39511. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39512. result._minX = parsedMesh.minX;
  39513. result._maxX = parsedMesh.maxX;
  39514. result._minZ = parsedMesh.minZ;
  39515. result._maxZ = parsedMesh.maxZ;
  39516. result._width = parsedMesh.width;
  39517. result._height = parsedMesh.height;
  39518. return result;
  39519. };
  39520. return GroundMesh;
  39521. }(BABYLON.Mesh));
  39522. BABYLON.GroundMesh = GroundMesh;
  39523. })(BABYLON || (BABYLON = {}));
  39524. //# sourceMappingURL=babylon.groundMesh.js.map
  39525. var BABYLON;
  39526. (function (BABYLON) {
  39527. /**
  39528. * Creates an instance based on a source mesh.
  39529. */
  39530. var InstancedMesh = (function (_super) {
  39531. __extends(InstancedMesh, _super);
  39532. function InstancedMesh(name, source) {
  39533. var _this = _super.call(this, name, source.getScene()) || this;
  39534. source.instances.push(_this);
  39535. _this._sourceMesh = source;
  39536. _this.position.copyFrom(source.position);
  39537. _this.rotation.copyFrom(source.rotation);
  39538. _this.scaling.copyFrom(source.scaling);
  39539. if (source.rotationQuaternion) {
  39540. _this.rotationQuaternion = source.rotationQuaternion.clone();
  39541. }
  39542. _this.infiniteDistance = source.infiniteDistance;
  39543. _this.setPivotMatrix(source.getPivotMatrix());
  39544. _this.refreshBoundingInfo();
  39545. _this._syncSubMeshes();
  39546. return _this;
  39547. }
  39548. /**
  39549. * Returns the string "InstancedMesh".
  39550. */
  39551. InstancedMesh.prototype.getClassName = function () {
  39552. return "InstancedMesh";
  39553. };
  39554. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  39555. // Methods
  39556. get: function () {
  39557. return this._sourceMesh.receiveShadows;
  39558. },
  39559. enumerable: true,
  39560. configurable: true
  39561. });
  39562. Object.defineProperty(InstancedMesh.prototype, "material", {
  39563. get: function () {
  39564. return this._sourceMesh.material;
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  39570. get: function () {
  39571. return this._sourceMesh.visibility;
  39572. },
  39573. enumerable: true,
  39574. configurable: true
  39575. });
  39576. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  39577. get: function () {
  39578. return this._sourceMesh.skeleton;
  39579. },
  39580. enumerable: true,
  39581. configurable: true
  39582. });
  39583. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  39584. get: function () {
  39585. return this._sourceMesh.renderingGroupId;
  39586. },
  39587. enumerable: true,
  39588. configurable: true
  39589. });
  39590. /**
  39591. * Returns the total number of vertices (integer).
  39592. */
  39593. InstancedMesh.prototype.getTotalVertices = function () {
  39594. return this._sourceMesh.getTotalVertices();
  39595. };
  39596. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  39597. get: function () {
  39598. return this._sourceMesh;
  39599. },
  39600. enumerable: true,
  39601. configurable: true
  39602. });
  39603. /**
  39604. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  39605. */
  39606. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  39607. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  39608. };
  39609. /**
  39610. * Sets the vertex data of the mesh geometry for the requested `kind`.
  39611. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  39612. * The `data` are either a numeric array either a Float32Array.
  39613. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  39614. * 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).
  39615. * Note that a new underlying VertexBuffer object is created each call.
  39616. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  39617. *
  39618. * Possible `kind` values :
  39619. * - BABYLON.VertexBuffer.PositionKind
  39620. * - BABYLON.VertexBuffer.UVKind
  39621. * - BABYLON.VertexBuffer.UV2Kind
  39622. * - BABYLON.VertexBuffer.UV3Kind
  39623. * - BABYLON.VertexBuffer.UV4Kind
  39624. * - BABYLON.VertexBuffer.UV5Kind
  39625. * - BABYLON.VertexBuffer.UV6Kind
  39626. * - BABYLON.VertexBuffer.ColorKind
  39627. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39628. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39629. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39630. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39631. *
  39632. * Returns the Mesh.
  39633. */
  39634. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39635. if (this.sourceMesh) {
  39636. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  39637. }
  39638. return this.sourceMesh;
  39639. };
  39640. /**
  39641. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  39642. * If the mesh has no geometry, it is simply returned as it is.
  39643. * The `data` are either a numeric array either a Float32Array.
  39644. * No new underlying VertexBuffer object is created.
  39645. * 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.
  39646. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  39647. *
  39648. * Possible `kind` values :
  39649. * - BABYLON.VertexBuffer.PositionKind
  39650. * - BABYLON.VertexBuffer.UVKind
  39651. * - BABYLON.VertexBuffer.UV2Kind
  39652. * - BABYLON.VertexBuffer.UV3Kind
  39653. * - BABYLON.VertexBuffer.UV4Kind
  39654. * - BABYLON.VertexBuffer.UV5Kind
  39655. * - BABYLON.VertexBuffer.UV6Kind
  39656. * - BABYLON.VertexBuffer.ColorKind
  39657. * - BABYLON.VertexBuffer.MatricesIndicesKind
  39658. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  39659. * - BABYLON.VertexBuffer.MatricesWeightsKind
  39660. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  39661. *
  39662. * Returns the Mesh.
  39663. */
  39664. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  39665. if (this.sourceMesh) {
  39666. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  39667. }
  39668. return this.sourceMesh;
  39669. };
  39670. /**
  39671. * Sets the mesh indices.
  39672. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  39673. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  39674. * This method creates a new index buffer each call.
  39675. * Returns the Mesh.
  39676. */
  39677. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  39678. if (this.sourceMesh) {
  39679. this.sourceMesh.setIndices(indices, totalVertices);
  39680. }
  39681. return this.sourceMesh;
  39682. };
  39683. /**
  39684. * Boolean : True if the mesh owns the requested kind of data.
  39685. */
  39686. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  39687. return this._sourceMesh.isVerticesDataPresent(kind);
  39688. };
  39689. /**
  39690. * Returns an array of indices (IndicesArray).
  39691. */
  39692. InstancedMesh.prototype.getIndices = function () {
  39693. return this._sourceMesh.getIndices();
  39694. };
  39695. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  39696. get: function () {
  39697. return this._sourceMesh._positions;
  39698. },
  39699. enumerable: true,
  39700. configurable: true
  39701. });
  39702. /**
  39703. * Sets a new updated BoundingInfo to the mesh.
  39704. * Returns the mesh.
  39705. */
  39706. InstancedMesh.prototype.refreshBoundingInfo = function () {
  39707. var meshBB = this._sourceMesh.getBoundingInfo();
  39708. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  39709. this._updateBoundingInfo();
  39710. return this;
  39711. };
  39712. InstancedMesh.prototype._preActivate = function () {
  39713. if (this._currentLOD) {
  39714. this._currentLOD._preActivate();
  39715. }
  39716. return this;
  39717. };
  39718. InstancedMesh.prototype._activate = function (renderId) {
  39719. if (this._currentLOD) {
  39720. this._currentLOD._registerInstanceForRenderId(this, renderId);
  39721. }
  39722. return this;
  39723. };
  39724. /**
  39725. * Returns the current associated LOD AbstractMesh.
  39726. */
  39727. InstancedMesh.prototype.getLOD = function (camera) {
  39728. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  39729. if (this._currentLOD === this.sourceMesh) {
  39730. return this;
  39731. }
  39732. return this._currentLOD;
  39733. };
  39734. InstancedMesh.prototype._syncSubMeshes = function () {
  39735. this.releaseSubMeshes();
  39736. if (this._sourceMesh.subMeshes) {
  39737. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  39738. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  39739. }
  39740. }
  39741. return this;
  39742. };
  39743. InstancedMesh.prototype._generatePointsArray = function () {
  39744. return this._sourceMesh._generatePointsArray();
  39745. };
  39746. /**
  39747. * Creates a new InstancedMesh from the current mesh.
  39748. * - name (string) : the cloned mesh name
  39749. * - newParent (optional Node) : the optional Node to parent the clone to.
  39750. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  39751. *
  39752. * Returns the clone.
  39753. */
  39754. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39755. var result = this._sourceMesh.createInstance(name);
  39756. // Deep copy
  39757. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  39758. // Bounding info
  39759. this.refreshBoundingInfo();
  39760. // Parent
  39761. if (newParent) {
  39762. result.parent = newParent;
  39763. }
  39764. if (!doNotCloneChildren) {
  39765. // Children
  39766. for (var index = 0; index < this.getScene().meshes.length; index++) {
  39767. var mesh = this.getScene().meshes[index];
  39768. if (mesh.parent === this) {
  39769. mesh.clone(mesh.name, result);
  39770. }
  39771. }
  39772. }
  39773. result.computeWorldMatrix(true);
  39774. return result;
  39775. };
  39776. /**
  39777. * Disposes the InstancedMesh.
  39778. * Returns nothing.
  39779. */
  39780. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  39781. // Remove from mesh
  39782. var index = this._sourceMesh.instances.indexOf(this);
  39783. this._sourceMesh.instances.splice(index, 1);
  39784. _super.prototype.dispose.call(this, doNotRecurse);
  39785. };
  39786. return InstancedMesh;
  39787. }(BABYLON.AbstractMesh));
  39788. BABYLON.InstancedMesh = InstancedMesh;
  39789. })(BABYLON || (BABYLON = {}));
  39790. //# sourceMappingURL=babylon.instancedMesh.js.map
  39791. /// <reference path="babylon.mesh.ts" />
  39792. var BABYLON;
  39793. (function (BABYLON) {
  39794. var LinesMesh = (function (_super) {
  39795. __extends(LinesMesh, _super);
  39796. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  39797. if (parent === void 0) { parent = null; }
  39798. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  39799. _this.useVertexColor = useVertexColor;
  39800. _this.color = new BABYLON.Color3(1, 1, 1);
  39801. _this.alpha = 1;
  39802. if (source) {
  39803. _this.color = source.color.clone();
  39804. _this.alpha = source.alpha;
  39805. _this.useVertexColor = source.useVertexColor;
  39806. }
  39807. _this._intersectionThreshold = 0.1;
  39808. var options = {
  39809. attributes: [BABYLON.VertexBuffer.PositionKind],
  39810. uniforms: ["world", "viewProjection"],
  39811. needAlphaBlending: false,
  39812. };
  39813. if (!useVertexColor) {
  39814. options.uniforms.push("color");
  39815. options.needAlphaBlending = true;
  39816. }
  39817. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  39818. return _this;
  39819. }
  39820. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  39821. /**
  39822. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39823. * This margin is expressed in world space coordinates, so its value may vary.
  39824. * Default value is 0.1
  39825. * @returns the intersection Threshold value.
  39826. */
  39827. get: function () {
  39828. return this._intersectionThreshold;
  39829. },
  39830. /**
  39831. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  39832. * This margin is expressed in world space coordinates, so its value may vary.
  39833. * @param value the new threshold to apply
  39834. */
  39835. set: function (value) {
  39836. if (this._intersectionThreshold === value) {
  39837. return;
  39838. }
  39839. this._intersectionThreshold = value;
  39840. if (this.geometry) {
  39841. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  39842. }
  39843. },
  39844. enumerable: true,
  39845. configurable: true
  39846. });
  39847. /**
  39848. * Returns the string "LineMesh"
  39849. */
  39850. LinesMesh.prototype.getClassName = function () {
  39851. return "LinesMesh";
  39852. };
  39853. Object.defineProperty(LinesMesh.prototype, "material", {
  39854. get: function () {
  39855. return this._colorShader;
  39856. },
  39857. enumerable: true,
  39858. configurable: true
  39859. });
  39860. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  39861. get: function () {
  39862. return false;
  39863. },
  39864. enumerable: true,
  39865. configurable: true
  39866. });
  39867. LinesMesh.prototype.createInstance = function (name) {
  39868. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  39869. return null;
  39870. };
  39871. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  39872. // VBOs
  39873. this._geometry._bind(this._colorShader.getEffect());
  39874. // Color
  39875. if (!this.useVertexColor) {
  39876. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  39877. }
  39878. return this;
  39879. };
  39880. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  39881. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  39882. return this;
  39883. }
  39884. var engine = this.getScene().getEngine();
  39885. // Draw order
  39886. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  39887. return this;
  39888. };
  39889. LinesMesh.prototype.dispose = function (doNotRecurse) {
  39890. this._colorShader.dispose();
  39891. _super.prototype.dispose.call(this, doNotRecurse);
  39892. };
  39893. /**
  39894. * Returns a new LineMesh object cloned from the current one.
  39895. */
  39896. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  39897. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  39898. };
  39899. return LinesMesh;
  39900. }(BABYLON.Mesh));
  39901. BABYLON.LinesMesh = LinesMesh;
  39902. })(BABYLON || (BABYLON = {}));
  39903. //# sourceMappingURL=babylon.linesMesh.js.map
  39904. var BABYLON;
  39905. (function (BABYLON) {
  39906. var ShaderMaterial = (function (_super) {
  39907. __extends(ShaderMaterial, _super);
  39908. function ShaderMaterial(name, scene, shaderPath, options) {
  39909. var _this = _super.call(this, name, scene) || this;
  39910. _this._textures = {};
  39911. _this._textureArrays = {};
  39912. _this._floats = {};
  39913. _this._floatsArrays = {};
  39914. _this._colors3 = {};
  39915. _this._colors4 = {};
  39916. _this._vectors2 = {};
  39917. _this._vectors3 = {};
  39918. _this._vectors4 = {};
  39919. _this._matrices = {};
  39920. _this._matrices3x3 = {};
  39921. _this._matrices2x2 = {};
  39922. _this._vectors3Arrays = {};
  39923. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39924. _this._shaderPath = shaderPath;
  39925. options.needAlphaBlending = options.needAlphaBlending || false;
  39926. options.needAlphaTesting = options.needAlphaTesting || false;
  39927. options.attributes = options.attributes || ["position", "normal", "uv"];
  39928. options.uniforms = options.uniforms || ["worldViewProjection"];
  39929. options.uniformBuffers = options.uniformBuffers || [];
  39930. options.samplers = options.samplers || [];
  39931. options.defines = options.defines || [];
  39932. _this._options = options;
  39933. return _this;
  39934. }
  39935. ShaderMaterial.prototype.getClassName = function () {
  39936. return "ShaderMaterial";
  39937. };
  39938. ShaderMaterial.prototype.needAlphaBlending = function () {
  39939. return this._options.needAlphaBlending;
  39940. };
  39941. ShaderMaterial.prototype.needAlphaTesting = function () {
  39942. return this._options.needAlphaTesting;
  39943. };
  39944. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39945. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39946. this._options.uniforms.push(uniformName);
  39947. }
  39948. };
  39949. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39950. if (this._options.samplers.indexOf(name) === -1) {
  39951. this._options.samplers.push(name);
  39952. }
  39953. this._textures[name] = texture;
  39954. return this;
  39955. };
  39956. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39957. if (this._options.samplers.indexOf(name) === -1) {
  39958. this._options.samplers.push(name);
  39959. }
  39960. this._checkUniform(name);
  39961. this._textureArrays[name] = textures;
  39962. return this;
  39963. };
  39964. ShaderMaterial.prototype.setFloat = function (name, value) {
  39965. this._checkUniform(name);
  39966. this._floats[name] = value;
  39967. return this;
  39968. };
  39969. ShaderMaterial.prototype.setFloats = function (name, value) {
  39970. this._checkUniform(name);
  39971. this._floatsArrays[name] = value;
  39972. return this;
  39973. };
  39974. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39975. this._checkUniform(name);
  39976. this._colors3[name] = value;
  39977. return this;
  39978. };
  39979. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39980. this._checkUniform(name);
  39981. this._colors4[name] = value;
  39982. return this;
  39983. };
  39984. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39985. this._checkUniform(name);
  39986. this._vectors2[name] = value;
  39987. return this;
  39988. };
  39989. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39990. this._checkUniform(name);
  39991. this._vectors3[name] = value;
  39992. return this;
  39993. };
  39994. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39995. this._checkUniform(name);
  39996. this._vectors4[name] = value;
  39997. return this;
  39998. };
  39999. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40000. this._checkUniform(name);
  40001. this._matrices[name] = value;
  40002. return this;
  40003. };
  40004. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40005. this._checkUniform(name);
  40006. this._matrices3x3[name] = value;
  40007. return this;
  40008. };
  40009. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40010. this._checkUniform(name);
  40011. this._matrices2x2[name] = value;
  40012. return this;
  40013. };
  40014. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40015. this._checkUniform(name);
  40016. this._vectors3Arrays[name] = value;
  40017. return this;
  40018. };
  40019. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40020. if (!mesh) {
  40021. return true;
  40022. }
  40023. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40024. return false;
  40025. }
  40026. return false;
  40027. };
  40028. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40029. var scene = this.getScene();
  40030. var engine = scene.getEngine();
  40031. if (!this.checkReadyOnEveryCall) {
  40032. if (this._renderId === scene.getRenderId()) {
  40033. if (this._checkCache(scene, mesh, useInstances)) {
  40034. return true;
  40035. }
  40036. }
  40037. }
  40038. // Instances
  40039. var defines = [];
  40040. var attribs = [];
  40041. var fallbacks = new BABYLON.EffectFallbacks();
  40042. if (useInstances) {
  40043. defines.push("#define INSTANCES");
  40044. }
  40045. for (var index = 0; index < this._options.defines.length; index++) {
  40046. defines.push(this._options.defines[index]);
  40047. }
  40048. for (var index = 0; index < this._options.attributes.length; index++) {
  40049. attribs.push(this._options.attributes[index]);
  40050. }
  40051. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40052. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40053. defines.push("#define VERTEXCOLOR");
  40054. }
  40055. // Bones
  40056. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40057. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40058. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40059. if (mesh.numBoneInfluencers > 4) {
  40060. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40061. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40062. }
  40063. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40064. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40065. fallbacks.addCPUSkinningFallback(0, mesh);
  40066. }
  40067. else {
  40068. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40069. }
  40070. // Textures
  40071. for (var name in this._textures) {
  40072. if (!this._textures[name].isReady()) {
  40073. return false;
  40074. }
  40075. }
  40076. // Alpha test
  40077. if (engine.getAlphaTesting()) {
  40078. defines.push("#define ALPHATEST");
  40079. }
  40080. var previousEffect = this._effect;
  40081. var join = defines.join("\n");
  40082. this._effect = engine.createEffect(this._shaderPath, {
  40083. attributes: attribs,
  40084. uniformsNames: this._options.uniforms,
  40085. uniformBuffersNames: this._options.uniformBuffers,
  40086. samplers: this._options.samplers,
  40087. defines: join,
  40088. fallbacks: fallbacks,
  40089. onCompiled: this.onCompiled,
  40090. onError: this.onError
  40091. }, engine);
  40092. if (!this._effect.isReady()) {
  40093. return false;
  40094. }
  40095. if (previousEffect !== this._effect) {
  40096. scene.resetCachedMaterial();
  40097. }
  40098. this._renderId = scene.getRenderId();
  40099. return true;
  40100. };
  40101. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40102. var scene = this.getScene();
  40103. if (this._options.uniforms.indexOf("world") !== -1) {
  40104. this._effect.setMatrix("world", world);
  40105. }
  40106. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40107. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40108. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40109. }
  40110. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40111. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40112. }
  40113. };
  40114. ShaderMaterial.prototype.bind = function (world, mesh) {
  40115. // Std values
  40116. this.bindOnlyWorldMatrix(world);
  40117. if (this.getScene().getCachedMaterial() !== this) {
  40118. if (this._options.uniforms.indexOf("view") !== -1) {
  40119. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40120. }
  40121. if (this._options.uniforms.indexOf("projection") !== -1) {
  40122. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40123. }
  40124. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40125. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40126. }
  40127. // Bones
  40128. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40129. var name;
  40130. // Texture
  40131. for (name in this._textures) {
  40132. this._effect.setTexture(name, this._textures[name]);
  40133. }
  40134. // Texture arrays
  40135. for (name in this._textureArrays) {
  40136. this._effect.setTextureArray(name, this._textureArrays[name]);
  40137. }
  40138. // Float
  40139. for (name in this._floats) {
  40140. this._effect.setFloat(name, this._floats[name]);
  40141. }
  40142. // Float s
  40143. for (name in this._floatsArrays) {
  40144. this._effect.setArray(name, this._floatsArrays[name]);
  40145. }
  40146. // Color3
  40147. for (name in this._colors3) {
  40148. this._effect.setColor3(name, this._colors3[name]);
  40149. }
  40150. // Color4
  40151. for (name in this._colors4) {
  40152. var color = this._colors4[name];
  40153. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40154. }
  40155. // Vector2
  40156. for (name in this._vectors2) {
  40157. this._effect.setVector2(name, this._vectors2[name]);
  40158. }
  40159. // Vector3
  40160. for (name in this._vectors3) {
  40161. this._effect.setVector3(name, this._vectors3[name]);
  40162. }
  40163. // Vector4
  40164. for (name in this._vectors4) {
  40165. this._effect.setVector4(name, this._vectors4[name]);
  40166. }
  40167. // Matrix
  40168. for (name in this._matrices) {
  40169. this._effect.setMatrix(name, this._matrices[name]);
  40170. }
  40171. // Matrix 3x3
  40172. for (name in this._matrices3x3) {
  40173. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40174. }
  40175. // Matrix 2x2
  40176. for (name in this._matrices2x2) {
  40177. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40178. }
  40179. // Vector3Array
  40180. for (name in this._vectors3Arrays) {
  40181. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40182. }
  40183. }
  40184. this._afterBind(mesh);
  40185. };
  40186. ShaderMaterial.prototype.clone = function (name) {
  40187. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40188. return newShaderMaterial;
  40189. };
  40190. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40191. if (forceDisposeTextures) {
  40192. var name;
  40193. for (name in this._textures) {
  40194. this._textures[name].dispose();
  40195. }
  40196. for (name in this._textureArrays) {
  40197. var array = this._textureArrays[name];
  40198. for (var index = 0; index < array.length; index++) {
  40199. array[index].dispose();
  40200. }
  40201. }
  40202. }
  40203. this._textures = {};
  40204. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40205. };
  40206. ShaderMaterial.prototype.serialize = function () {
  40207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40208. serializationObject.customType = "BABYLON.ShaderMaterial";
  40209. serializationObject.options = this._options;
  40210. serializationObject.shaderPath = this._shaderPath;
  40211. var name;
  40212. // Texture
  40213. serializationObject.textures = {};
  40214. for (name in this._textures) {
  40215. serializationObject.textures[name] = this._textures[name].serialize();
  40216. }
  40217. // Texture arrays
  40218. serializationObject.textureArrays = {};
  40219. for (name in this._textureArrays) {
  40220. serializationObject.textureArrays[name] = [];
  40221. var array = this._textureArrays[name];
  40222. for (var index = 0; index < array.length; index++) {
  40223. serializationObject.textureArrays[name].push(array[index].serialize());
  40224. }
  40225. }
  40226. // Float
  40227. serializationObject.floats = {};
  40228. for (name in this._floats) {
  40229. serializationObject.floats[name] = this._floats[name];
  40230. }
  40231. // Float s
  40232. serializationObject.floatArrays = {};
  40233. for (name in this._floatsArrays) {
  40234. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40235. }
  40236. // Color3
  40237. serializationObject.colors3 = {};
  40238. for (name in this._colors3) {
  40239. serializationObject.colors3[name] = this._colors3[name].asArray();
  40240. }
  40241. // Color4
  40242. serializationObject.colors4 = {};
  40243. for (name in this._colors4) {
  40244. serializationObject.colors4[name] = this._colors4[name].asArray();
  40245. }
  40246. // Vector2
  40247. serializationObject.vectors2 = {};
  40248. for (name in this._vectors2) {
  40249. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40250. }
  40251. // Vector3
  40252. serializationObject.vectors3 = {};
  40253. for (name in this._vectors3) {
  40254. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40255. }
  40256. // Vector4
  40257. serializationObject.vectors4 = {};
  40258. for (name in this._vectors4) {
  40259. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40260. }
  40261. // Matrix
  40262. serializationObject.matrices = {};
  40263. for (name in this._matrices) {
  40264. serializationObject.matrices[name] = this._matrices[name].asArray();
  40265. }
  40266. // Matrix 3x3
  40267. serializationObject.matrices3x3 = {};
  40268. for (name in this._matrices3x3) {
  40269. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40270. }
  40271. // Matrix 2x2
  40272. serializationObject.matrices2x2 = {};
  40273. for (name in this._matrices2x2) {
  40274. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40275. }
  40276. // Vector3Array
  40277. serializationObject.vectors3Arrays = {};
  40278. for (name in this._vectors3Arrays) {
  40279. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40280. }
  40281. return serializationObject;
  40282. };
  40283. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40284. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40285. var name;
  40286. // Texture
  40287. for (name in source.textures) {
  40288. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40289. }
  40290. // Texture arrays
  40291. for (name in source.textureArrays) {
  40292. var array = source.textureArrays[name];
  40293. var textureArray = new Array();
  40294. for (var index = 0; index < array.length; index++) {
  40295. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40296. }
  40297. material.setTextureArray(name, textureArray);
  40298. }
  40299. // Float
  40300. for (name in source.floats) {
  40301. material.setFloat(name, source.floats[name]);
  40302. }
  40303. // Float s
  40304. for (name in source.floatsArrays) {
  40305. material.setFloats(name, source.floatsArrays[name]);
  40306. }
  40307. // Color3
  40308. for (name in source.colors3) {
  40309. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40310. }
  40311. // Color4
  40312. for (name in source.colors4) {
  40313. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40314. }
  40315. // Vector2
  40316. for (name in source.vectors2) {
  40317. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40318. }
  40319. // Vector3
  40320. for (name in source.vectors3) {
  40321. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40322. }
  40323. // Vector4
  40324. for (name in source.vectors4) {
  40325. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40326. }
  40327. // Matrix
  40328. for (name in source.matrices) {
  40329. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40330. }
  40331. // Matrix 3x3
  40332. for (name in source.matrices3x3) {
  40333. material.setMatrix3x3(name, source.matrices3x3[name]);
  40334. }
  40335. // Matrix 2x2
  40336. for (name in source.matrices2x2) {
  40337. material.setMatrix2x2(name, source.matrices2x2[name]);
  40338. }
  40339. // Vector3Array
  40340. for (name in source.vectors3Arrays) {
  40341. material.setArray3(name, source.vectors3Arrays[name]);
  40342. }
  40343. return material;
  40344. };
  40345. return ShaderMaterial;
  40346. }(BABYLON.Material));
  40347. BABYLON.ShaderMaterial = ShaderMaterial;
  40348. })(BABYLON || (BABYLON = {}));
  40349. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40350. var BABYLON;
  40351. (function (BABYLON) {
  40352. var MeshBuilder = (function () {
  40353. function MeshBuilder() {
  40354. }
  40355. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  40356. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  40357. return BABYLON.Mesh.DOUBLESIDE;
  40358. }
  40359. if (orientation === undefined || orientation === null) {
  40360. return BABYLON.Mesh.FRONTSIDE;
  40361. }
  40362. return orientation;
  40363. };
  40364. /**
  40365. * Creates a box mesh.
  40366. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  40367. * The parameter `size` sets the size (float) of each box side (default 1).
  40368. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  40369. * 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).
  40370. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  40371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40372. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40375. */
  40376. MeshBuilder.CreateBox = function (name, options, scene) {
  40377. var box = new BABYLON.Mesh(name, scene);
  40378. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40379. box.sideOrientation = options.sideOrientation;
  40380. var vertexData = BABYLON.VertexData.CreateBox(options);
  40381. vertexData.applyToMesh(box, options.updatable);
  40382. return box;
  40383. };
  40384. /**
  40385. * Creates a sphere mesh.
  40386. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  40387. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  40388. * 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`).
  40389. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  40390. * 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
  40391. * 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).
  40392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40393. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40396. */
  40397. MeshBuilder.CreateSphere = function (name, options, scene) {
  40398. var sphere = new BABYLON.Mesh(name, scene);
  40399. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40400. sphere.sideOrientation = options.sideOrientation;
  40401. var vertexData = BABYLON.VertexData.CreateSphere(options);
  40402. vertexData.applyToMesh(sphere, options.updatable);
  40403. return sphere;
  40404. };
  40405. /**
  40406. * Creates a plane polygonal mesh. By default, this is a disc.
  40407. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  40408. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  40409. * 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.
  40410. * 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
  40411. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40412. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40413. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40415. */
  40416. MeshBuilder.CreateDisc = function (name, options, scene) {
  40417. var disc = new BABYLON.Mesh(name, scene);
  40418. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40419. disc.sideOrientation = options.sideOrientation;
  40420. var vertexData = BABYLON.VertexData.CreateDisc(options);
  40421. vertexData.applyToMesh(disc, options.updatable);
  40422. return disc;
  40423. };
  40424. /**
  40425. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  40426. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  40427. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  40428. * 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`).
  40429. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  40430. * 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.
  40431. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40432. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40433. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40435. */
  40436. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  40437. var sphere = new BABYLON.Mesh(name, scene);
  40438. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40439. sphere.sideOrientation = options.sideOrientation;
  40440. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  40441. vertexData.applyToMesh(sphere, options.updatable);
  40442. return sphere;
  40443. };
  40444. ;
  40445. /**
  40446. * Creates a ribbon mesh.
  40447. * 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.
  40448. *
  40449. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  40450. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  40451. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  40452. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  40453. * 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.
  40454. * 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.
  40455. * 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
  40456. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40457. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40458. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40459. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40460. * 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.
  40461. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  40462. * 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
  40463. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  40464. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  40465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40466. */
  40467. MeshBuilder.CreateRibbon = function (name, options, scene) {
  40468. var pathArray = options.pathArray;
  40469. var closeArray = options.closeArray;
  40470. var closePath = options.closePath;
  40471. var offset = options.offset;
  40472. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40473. var instance = options.instance;
  40474. var updatable = options.updatable;
  40475. if (instance) {
  40476. // positionFunction : ribbon case
  40477. // only pathArray and sideOrientation parameters are taken into account for positions update
  40478. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  40479. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  40480. var positionFunction = function (positions) {
  40481. var minlg = pathArray[0].length;
  40482. var i = 0;
  40483. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  40484. for (var si = 1; si <= ns; si++) {
  40485. for (var p = 0; p < pathArray.length; p++) {
  40486. var path = pathArray[p];
  40487. var l = path.length;
  40488. minlg = (minlg < l) ? minlg : l;
  40489. var j = 0;
  40490. while (j < minlg) {
  40491. positions[i] = path[j].x;
  40492. positions[i + 1] = path[j].y;
  40493. positions[i + 2] = path[j].z;
  40494. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  40495. BABYLON.Tmp.Vector3[0].x = path[j].x;
  40496. }
  40497. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  40498. BABYLON.Tmp.Vector3[1].x = path[j].x;
  40499. }
  40500. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  40501. BABYLON.Tmp.Vector3[0].y = path[j].y;
  40502. }
  40503. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  40504. BABYLON.Tmp.Vector3[1].y = path[j].y;
  40505. }
  40506. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  40507. BABYLON.Tmp.Vector3[0].z = path[j].z;
  40508. }
  40509. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  40510. BABYLON.Tmp.Vector3[1].z = path[j].z;
  40511. }
  40512. j++;
  40513. i += 3;
  40514. }
  40515. if (instance._closePath) {
  40516. positions[i] = path[0].x;
  40517. positions[i + 1] = path[0].y;
  40518. positions[i + 2] = path[0].z;
  40519. i += 3;
  40520. }
  40521. }
  40522. }
  40523. };
  40524. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40525. positionFunction(positions);
  40526. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  40527. instance._boundingInfo.update(instance._worldMatrix);
  40528. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  40529. if (options.colors) {
  40530. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40531. for (var c = 0; c < options.colors.length; c++) {
  40532. colors[c * 4] = options.colors[c].r;
  40533. colors[c * 4 + 1] = options.colors[c].g;
  40534. colors[c * 4 + 2] = options.colors[c].b;
  40535. colors[c * 4 + 3] = options.colors[c].a;
  40536. }
  40537. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  40538. }
  40539. if (options.uvs) {
  40540. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40541. for (var i = 0; i < options.uvs.length; i++) {
  40542. uvs[i * 2] = options.uvs[i].x;
  40543. uvs[i * 2 + 1] = options.uvs[i].y;
  40544. }
  40545. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  40546. }
  40547. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  40548. var indices = instance.getIndices();
  40549. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40550. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  40551. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  40552. if (instance._closePath) {
  40553. var indexFirst = 0;
  40554. var indexLast = 0;
  40555. for (var p = 0; p < pathArray.length; p++) {
  40556. indexFirst = instance._idx[p] * 3;
  40557. if (p + 1 < pathArray.length) {
  40558. indexLast = (instance._idx[p + 1] - 1) * 3;
  40559. }
  40560. else {
  40561. indexLast = normals.length - 3;
  40562. }
  40563. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  40564. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  40565. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  40566. normals[indexLast] = normals[indexFirst];
  40567. normals[indexLast + 1] = normals[indexFirst + 1];
  40568. normals[indexLast + 2] = normals[indexFirst + 2];
  40569. }
  40570. }
  40571. if (!(instance.areNormalsFrozen)) {
  40572. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  40573. }
  40574. }
  40575. return instance;
  40576. }
  40577. else {
  40578. var ribbon = new BABYLON.Mesh(name, scene);
  40579. ribbon.sideOrientation = sideOrientation;
  40580. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  40581. if (closePath) {
  40582. ribbon._idx = vertexData._idx;
  40583. }
  40584. ribbon._closePath = closePath;
  40585. ribbon._closeArray = closeArray;
  40586. vertexData.applyToMesh(ribbon, updatable);
  40587. return ribbon;
  40588. }
  40589. };
  40590. /**
  40591. * Creates a cylinder or a cone mesh.
  40592. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  40593. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  40594. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  40595. * 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.
  40596. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  40597. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  40598. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  40599. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  40600. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  40601. * 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).
  40602. * 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
  40603. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  40604. * 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
  40605. * 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.
  40606. * If `enclose` is false, a ring surface is one element.
  40607. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  40608. * 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
  40609. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40610. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40611. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40612. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40613. */
  40614. MeshBuilder.CreateCylinder = function (name, options, scene) {
  40615. var cylinder = new BABYLON.Mesh(name, scene);
  40616. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40617. cylinder.sideOrientation = options.sideOrientation;
  40618. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  40619. vertexData.applyToMesh(cylinder, options.updatable);
  40620. return cylinder;
  40621. };
  40622. /**
  40623. * Creates a torus mesh.
  40624. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  40625. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  40626. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  40627. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  40628. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40629. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40632. */
  40633. MeshBuilder.CreateTorus = function (name, options, scene) {
  40634. var torus = new BABYLON.Mesh(name, scene);
  40635. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40636. torus.sideOrientation = options.sideOrientation;
  40637. var vertexData = BABYLON.VertexData.CreateTorus(options);
  40638. vertexData.applyToMesh(torus, options.updatable);
  40639. return torus;
  40640. };
  40641. /**
  40642. * Creates a torus knot mesh.
  40643. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  40644. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  40645. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  40646. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  40647. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  40648. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40649. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40652. */
  40653. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  40654. var torusKnot = new BABYLON.Mesh(name, scene);
  40655. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40656. torusKnot.sideOrientation = options.sideOrientation;
  40657. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  40658. vertexData.applyToMesh(torusKnot, options.updatable);
  40659. return torusKnot;
  40660. };
  40661. /**
  40662. * Creates a line system mesh.
  40663. * A line system is a pool of many lines gathered in a single mesh.
  40664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  40665. * 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.
  40666. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  40667. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  40668. * 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
  40669. * 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
  40670. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  40671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40672. */
  40673. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  40674. var instance = options.instance;
  40675. var lines = options.lines;
  40676. if (instance) {
  40677. var positionFunction = function (positions) {
  40678. var i = 0;
  40679. for (var l = 0; l < lines.length; l++) {
  40680. var points = lines[l];
  40681. for (var p = 0; p < points.length; p++) {
  40682. positions[i] = points[p].x;
  40683. positions[i + 1] = points[p].y;
  40684. positions[i + 2] = points[p].z;
  40685. i += 3;
  40686. }
  40687. }
  40688. };
  40689. instance.updateMeshPositions(positionFunction, false);
  40690. return instance;
  40691. }
  40692. // line system creation
  40693. var lineSystem = new BABYLON.LinesMesh(name, scene);
  40694. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  40695. vertexData.applyToMesh(lineSystem, options.updatable);
  40696. return lineSystem;
  40697. };
  40698. /**
  40699. * Creates a line mesh.
  40700. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  40701. * 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.
  40702. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40703. * The parameter `points` is an array successive Vector3.
  40704. * 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
  40705. * When updating an instance, remember that only point positions can change, not the number of points.
  40706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40707. */
  40708. MeshBuilder.CreateLines = function (name, options, scene) {
  40709. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  40710. return lines;
  40711. };
  40712. /**
  40713. * Creates a dashed line mesh.
  40714. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  40715. * 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.
  40716. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  40717. * The parameter `points` is an array successive Vector3.
  40718. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  40719. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  40720. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  40721. * 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
  40722. * When updating an instance, remember that only point positions can change, not the number of points.
  40723. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40724. */
  40725. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  40726. var points = options.points;
  40727. var instance = options.instance;
  40728. var gapSize = options.gapSize;
  40729. var dashNb = options.dashNb;
  40730. var dashSize = options.dashSize;
  40731. if (instance) {
  40732. var positionFunction = function (positions) {
  40733. var curvect = BABYLON.Vector3.Zero();
  40734. var nbSeg = positions.length / 6;
  40735. var lg = 0;
  40736. var nb = 0;
  40737. var shft = 0;
  40738. var dashshft = 0;
  40739. var curshft = 0;
  40740. var p = 0;
  40741. var i = 0;
  40742. var j = 0;
  40743. for (i = 0; i < points.length - 1; i++) {
  40744. points[i + 1].subtractToRef(points[i], curvect);
  40745. lg += curvect.length();
  40746. }
  40747. shft = lg / nbSeg;
  40748. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  40749. for (i = 0; i < points.length - 1; i++) {
  40750. points[i + 1].subtractToRef(points[i], curvect);
  40751. nb = Math.floor(curvect.length() / shft);
  40752. curvect.normalize();
  40753. j = 0;
  40754. while (j < nb && p < positions.length) {
  40755. curshft = shft * j;
  40756. positions[p] = points[i].x + curshft * curvect.x;
  40757. positions[p + 1] = points[i].y + curshft * curvect.y;
  40758. positions[p + 2] = points[i].z + curshft * curvect.z;
  40759. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  40760. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  40761. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  40762. p += 6;
  40763. j++;
  40764. }
  40765. }
  40766. while (p < positions.length) {
  40767. positions[p] = points[i].x;
  40768. positions[p + 1] = points[i].y;
  40769. positions[p + 2] = points[i].z;
  40770. p += 3;
  40771. }
  40772. };
  40773. instance.updateMeshPositions(positionFunction, false);
  40774. return instance;
  40775. }
  40776. // dashed lines creation
  40777. var dashedLines = new BABYLON.LinesMesh(name, scene);
  40778. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  40779. vertexData.applyToMesh(dashedLines, options.updatable);
  40780. dashedLines.dashSize = dashSize;
  40781. dashedLines.gapSize = gapSize;
  40782. return dashedLines;
  40783. };
  40784. /**
  40785. * Creates an extruded shape mesh.
  40786. * 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.
  40787. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  40788. *
  40789. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40790. * 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
  40791. * extruded along the Z axis.
  40792. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40793. * 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.
  40794. * The parameter `scale` (float, default 1) is the value to scale the shape.
  40795. * 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
  40796. * 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
  40797. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40798. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40799. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40800. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40801. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40803. */
  40804. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  40805. var path = options.path;
  40806. var shape = options.shape;
  40807. var scale = options.scale || 1;
  40808. var rotation = options.rotation || 0;
  40809. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40810. var updatable = options.updatable;
  40811. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40812. var instance = options.instance;
  40813. var invertUV = options.invertUV || false;
  40814. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40815. };
  40816. /**
  40817. * Creates an custom extruded shape mesh.
  40818. * 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.
  40819. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  40820. *
  40821. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  40822. * 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
  40823. * extruded along the Z axis.
  40824. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  40825. * 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
  40826. * and the distance of this point from the begining of the path :
  40827. * ```javascript
  40828. * var rotationFunction = function(i, distance) {
  40829. * // do things
  40830. * return rotationValue; }
  40831. * ```
  40832. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  40833. * 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
  40834. * and the distance of this point from the begining of the path :
  40835. * ```javascript
  40836. * var scaleFunction = function(i, distance) {
  40837. * // do things
  40838. * return scaleValue;}
  40839. * ```
  40840. * It must returns a float value that will be the scale value applied to the shape on each path point.
  40841. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  40842. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  40843. * 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
  40844. * 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
  40845. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  40846. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40847. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40848. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40849. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40851. */
  40852. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  40853. var path = options.path;
  40854. var shape = options.shape;
  40855. var scaleFunction = options.scaleFunction || (function () { return 1; });
  40856. var rotationFunction = options.rotationFunction || (function () { return 0; });
  40857. var ribbonCloseArray = options.ribbonCloseArray || false;
  40858. var ribbonClosePath = options.ribbonClosePath || false;
  40859. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  40860. var updatable = options.updatable;
  40861. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40862. var instance = options.instance;
  40863. var invertUV = options.invertUV || false;
  40864. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  40865. };
  40866. /**
  40867. * Creates lathe mesh.
  40868. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  40869. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  40870. *
  40871. * 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
  40872. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  40873. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  40874. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  40875. * 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.
  40876. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  40877. * 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
  40878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40879. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40880. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40881. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  40882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40883. */
  40884. MeshBuilder.CreateLathe = function (name, options, scene) {
  40885. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  40886. var closed = (options.closed === undefined) ? true : options.closed;
  40887. var shape = options.shape;
  40888. var radius = options.radius || 1;
  40889. var tessellation = options.tessellation || 64;
  40890. var updatable = options.updatable;
  40891. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40892. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  40893. var pi2 = Math.PI * 2;
  40894. var paths = new Array();
  40895. var invertUV = options.invertUV || false;
  40896. var i = 0;
  40897. var p = 0;
  40898. var step = pi2 / tessellation * arc;
  40899. var rotated;
  40900. var path = new Array();
  40901. ;
  40902. for (i = 0; i <= tessellation; i++) {
  40903. var path = [];
  40904. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  40905. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  40906. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  40907. }
  40908. for (p = 0; p < shape.length; p++) {
  40909. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  40910. path.push(rotated);
  40911. }
  40912. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  40913. 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));
  40914. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  40915. }
  40916. paths.push(path);
  40917. }
  40918. // lathe ribbon
  40919. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  40920. return lathe;
  40921. };
  40922. /**
  40923. * Creates a plane mesh.
  40924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40925. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  40926. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  40927. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  40928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  40929. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  40930. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  40931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40932. */
  40933. MeshBuilder.CreatePlane = function (name, options, scene) {
  40934. var plane = new BABYLON.Mesh(name, scene);
  40935. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  40936. plane.sideOrientation = options.sideOrientation;
  40937. var vertexData = BABYLON.VertexData.CreatePlane(options);
  40938. vertexData.applyToMesh(plane, options.updatable);
  40939. if (options.sourcePlane) {
  40940. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  40941. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  40942. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  40943. plane.rotate(vectorProduct, product);
  40944. }
  40945. return plane;
  40946. };
  40947. /**
  40948. * Creates a ground mesh.
  40949. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  40950. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  40951. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  40952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40953. */
  40954. MeshBuilder.CreateGround = function (name, options, scene) {
  40955. var ground = new BABYLON.GroundMesh(name, scene);
  40956. ground._setReady(false);
  40957. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  40958. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  40959. ground._width = options.width || 1;
  40960. ground._height = options.height || 1;
  40961. ground._maxX = ground._width / 2;
  40962. ground._maxZ = ground._height / 2;
  40963. ground._minX = -ground._maxX;
  40964. ground._minZ = -ground._maxZ;
  40965. var vertexData = BABYLON.VertexData.CreateGround(options);
  40966. vertexData.applyToMesh(ground, options.updatable);
  40967. ground._setReady(true);
  40968. return ground;
  40969. };
  40970. /**
  40971. * Creates a tiled ground mesh.
  40972. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  40973. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  40974. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  40975. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  40976. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  40977. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  40978. * numbers of subdivisions on the ground width and height of each tile.
  40979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  40980. */
  40981. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  40982. var tiledGround = new BABYLON.Mesh(name, scene);
  40983. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  40984. vertexData.applyToMesh(tiledGround, options.updatable);
  40985. return tiledGround;
  40986. };
  40987. /**
  40988. * Creates a ground mesh from a height map.
  40989. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  40990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  40991. * The parameter `url` sets the URL of the height map image resource.
  40992. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  40993. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  40994. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  40995. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  40996. * 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.
  40997. * 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).
  40998. * This function is passed the newly built mesh :
  40999. * ```javascript
  41000. * function(mesh) { // do things
  41001. * return; }
  41002. * ```
  41003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41004. */
  41005. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  41006. var width = options.width || 10.0;
  41007. var height = options.height || 10.0;
  41008. var subdivisions = options.subdivisions || 1 | 0;
  41009. var minHeight = options.minHeight || 0.0;
  41010. var maxHeight = options.maxHeight || 10.0;
  41011. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  41012. var updatable = options.updatable;
  41013. var onReady = options.onReady;
  41014. var ground = new BABYLON.GroundMesh(name, scene);
  41015. ground._subdivisionsX = subdivisions;
  41016. ground._subdivisionsY = subdivisions;
  41017. ground._width = width;
  41018. ground._height = height;
  41019. ground._maxX = ground._width / 2.0;
  41020. ground._maxZ = ground._height / 2.0;
  41021. ground._minX = -ground._maxX;
  41022. ground._minZ = -ground._maxZ;
  41023. ground._setReady(false);
  41024. var onload = function (img) {
  41025. // Getting height map data
  41026. var canvas = document.createElement("canvas");
  41027. var context = canvas.getContext("2d");
  41028. var bufferWidth = img.width;
  41029. var bufferHeight = img.height;
  41030. canvas.width = bufferWidth;
  41031. canvas.height = bufferHeight;
  41032. context.drawImage(img, 0, 0);
  41033. // Create VertexData from map data
  41034. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  41035. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  41036. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  41037. width: width, height: height,
  41038. subdivisions: subdivisions,
  41039. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  41040. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  41041. });
  41042. vertexData.applyToMesh(ground, updatable);
  41043. ground._setReady(true);
  41044. //execute ready callback, if set
  41045. if (onReady) {
  41046. onReady(ground);
  41047. }
  41048. };
  41049. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  41050. return ground;
  41051. };
  41052. /**
  41053. * Creates a polygon mesh.
  41054. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  41055. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  41056. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41058. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  41059. * Remember you can only change the shape positions, not their number when updating a polygon.
  41060. */
  41061. MeshBuilder.CreatePolygon = function (name, options, scene) {
  41062. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41063. var shape = options.shape;
  41064. var holes = options.holes || [];
  41065. var depth = options.depth || 0;
  41066. var contours = [];
  41067. var hole = [];
  41068. for (var i = 0; i < shape.length; i++) {
  41069. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  41070. }
  41071. var epsilon = 0.00000001;
  41072. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  41073. contours.pop();
  41074. }
  41075. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  41076. for (var hNb = 0; hNb < holes.length; hNb++) {
  41077. hole = [];
  41078. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  41079. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  41080. }
  41081. polygonTriangulation.addHole(hole);
  41082. }
  41083. var polygon = polygonTriangulation.build(options.updatable, depth);
  41084. polygon.sideOrientation = options.sideOrientation;
  41085. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  41086. vertexData.applyToMesh(polygon, options.updatable);
  41087. return polygon;
  41088. };
  41089. ;
  41090. /**
  41091. * Creates an extruded polygon mesh, with depth in the Y direction.
  41092. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  41093. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  41094. */
  41095. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  41096. return MeshBuilder.CreatePolygon(name, options, scene);
  41097. };
  41098. ;
  41099. /**
  41100. * Creates a tube mesh.
  41101. * 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.
  41102. *
  41103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  41104. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  41105. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  41106. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  41107. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  41108. * 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.
  41109. * It must return a radius value (positive float) :
  41110. * ```javascript
  41111. * var radiusFunction = function(i, distance) {
  41112. * // do things
  41113. * return radius; }
  41114. * ```
  41115. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  41116. * 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
  41117. * 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
  41118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41119. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  41120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41121. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  41122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41123. */
  41124. MeshBuilder.CreateTube = function (name, options, scene) {
  41125. var path = options.path;
  41126. var radius = options.radius || 1.0;
  41127. var tessellation = options.tessellation || 64 | 0;
  41128. var radiusFunction = options.radiusFunction;
  41129. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  41130. var invertUV = options.invertUV || false;
  41131. var updatable = options.updatable;
  41132. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41133. var instance = options.instance;
  41134. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  41135. // tube geometry
  41136. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  41137. var tangents = path3D.getTangents();
  41138. var normals = path3D.getNormals();
  41139. var distances = path3D.getDistances();
  41140. var pi2 = Math.PI * 2;
  41141. var step = pi2 / tessellation * arc;
  41142. var returnRadius = function () { return radius; };
  41143. var radiusFunctionFinal = radiusFunction || returnRadius;
  41144. var circlePath;
  41145. var rad;
  41146. var normal;
  41147. var rotated;
  41148. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41149. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41150. for (var i = 0; i < path.length; i++) {
  41151. rad = radiusFunctionFinal(i, distances[i]); // current radius
  41152. circlePath = Array(); // current circle array
  41153. normal = normals[i]; // current normal
  41154. for (var t = 0; t < tessellation; t++) {
  41155. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  41156. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  41157. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  41158. rotated.scaleInPlace(rad).addInPlace(path[i]);
  41159. circlePath[t] = rotated;
  41160. }
  41161. circlePaths[index] = circlePath;
  41162. index++;
  41163. }
  41164. // cap
  41165. var capPath = function (nbPoints, pathIndex) {
  41166. var pointCap = Array();
  41167. for (var i = 0; i < nbPoints; i++) {
  41168. pointCap.push(path[pathIndex]);
  41169. }
  41170. return pointCap;
  41171. };
  41172. switch (cap) {
  41173. case BABYLON.Mesh.NO_CAP:
  41174. break;
  41175. case BABYLON.Mesh.CAP_START:
  41176. circlePaths[0] = capPath(tessellation, 0);
  41177. circlePaths[1] = circlePaths[2].slice(0);
  41178. break;
  41179. case BABYLON.Mesh.CAP_END:
  41180. circlePaths[index] = circlePaths[index - 1].slice(0);
  41181. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41182. break;
  41183. case BABYLON.Mesh.CAP_ALL:
  41184. circlePaths[0] = capPath(tessellation, 0);
  41185. circlePaths[1] = circlePaths[2].slice(0);
  41186. circlePaths[index] = circlePaths[index - 1].slice(0);
  41187. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  41188. break;
  41189. default:
  41190. break;
  41191. }
  41192. return circlePaths;
  41193. };
  41194. var path3D;
  41195. var pathArray;
  41196. if (instance) {
  41197. var arc = options.arc || instance.arc;
  41198. path3D = (instance.path3D).update(path);
  41199. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  41200. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  41201. instance.path3D = path3D;
  41202. instance.pathArray = pathArray;
  41203. instance.arc = arc;
  41204. return instance;
  41205. }
  41206. // tube creation
  41207. path3D = new BABYLON.Path3D(path);
  41208. var newPathArray = new Array();
  41209. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41210. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  41211. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  41212. tube.pathArray = pathArray;
  41213. tube.path3D = path3D;
  41214. tube.tessellation = tessellation;
  41215. tube.cap = cap;
  41216. tube.arc = options.arc;
  41217. return tube;
  41218. };
  41219. /**
  41220. * Creates a polyhedron mesh.
  41221. *
  41222. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  41223. * 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
  41224. * to choose the wanted type.
  41225. * The parameter `size` (positive float, default 1) sets the polygon size.
  41226. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  41227. * 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`.
  41228. * 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
  41229. * 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)`).
  41230. * 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
  41231. * 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.
  41232. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  41233. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  41234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  41235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  41236. */
  41237. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  41238. var polyhedron = new BABYLON.Mesh(name, scene);
  41239. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  41240. polyhedron.sideOrientation = options.sideOrientation;
  41241. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  41242. vertexData.applyToMesh(polyhedron, options.updatable);
  41243. return polyhedron;
  41244. };
  41245. /**
  41246. * Creates a decal mesh.
  41247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  41248. * 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.
  41249. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  41250. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  41251. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  41252. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  41253. */
  41254. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  41255. var indices = sourceMesh.getIndices();
  41256. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41257. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41258. var position = options.position || BABYLON.Vector3.Zero();
  41259. var normal = options.normal || BABYLON.Vector3.Up();
  41260. var size = options.size || BABYLON.Vector3.One();
  41261. var angle = options.angle || 0;
  41262. // Getting correct rotation
  41263. if (!normal) {
  41264. var target = new BABYLON.Vector3(0, 0, 1);
  41265. var camera = sourceMesh.getScene().activeCamera;
  41266. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  41267. normal = camera.globalPosition.subtract(cameraWorldTarget);
  41268. }
  41269. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  41270. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  41271. var pitch = Math.atan2(normal.y, len);
  41272. // Matrix
  41273. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  41274. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  41275. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  41276. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  41277. var vertexData = new BABYLON.VertexData();
  41278. vertexData.indices = [];
  41279. vertexData.positions = [];
  41280. vertexData.normals = [];
  41281. vertexData.uvs = [];
  41282. var currentVertexDataIndex = 0;
  41283. var extractDecalVector3 = function (indexId) {
  41284. var vertexId = indices[indexId];
  41285. var result = new BABYLON.PositionNormalVertex();
  41286. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  41287. // Send vector to decal local world
  41288. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  41289. // Get normal
  41290. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  41291. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  41292. return result;
  41293. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  41294. var clip = function (vertices, axis) {
  41295. if (vertices.length === 0) {
  41296. return vertices;
  41297. }
  41298. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  41299. var clipVertices = function (v0, v1) {
  41300. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  41301. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  41302. };
  41303. var result = new Array();
  41304. for (var index = 0; index < vertices.length; index += 3) {
  41305. var v1Out;
  41306. var v2Out;
  41307. var v3Out;
  41308. var total = 0;
  41309. var nV1, nV2, nV3, nV4;
  41310. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  41311. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  41312. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  41313. v1Out = d1 > 0;
  41314. v2Out = d2 > 0;
  41315. v3Out = d3 > 0;
  41316. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  41317. switch (total) {
  41318. case 0:
  41319. result.push(vertices[index]);
  41320. result.push(vertices[index + 1]);
  41321. result.push(vertices[index + 2]);
  41322. break;
  41323. case 1:
  41324. if (v1Out) {
  41325. nV1 = vertices[index + 1];
  41326. nV2 = vertices[index + 2];
  41327. nV3 = clipVertices(vertices[index], nV1);
  41328. nV4 = clipVertices(vertices[index], nV2);
  41329. }
  41330. if (v2Out) {
  41331. nV1 = vertices[index];
  41332. nV2 = vertices[index + 2];
  41333. nV3 = clipVertices(vertices[index + 1], nV1);
  41334. nV4 = clipVertices(vertices[index + 1], nV2);
  41335. result.push(nV3);
  41336. result.push(nV2.clone());
  41337. result.push(nV1.clone());
  41338. result.push(nV2.clone());
  41339. result.push(nV3.clone());
  41340. result.push(nV4);
  41341. break;
  41342. }
  41343. if (v3Out) {
  41344. nV1 = vertices[index];
  41345. nV2 = vertices[index + 1];
  41346. nV3 = clipVertices(vertices[index + 2], nV1);
  41347. nV4 = clipVertices(vertices[index + 2], nV2);
  41348. }
  41349. result.push(nV1.clone());
  41350. result.push(nV2.clone());
  41351. result.push(nV3);
  41352. result.push(nV4);
  41353. result.push(nV3.clone());
  41354. result.push(nV2.clone());
  41355. break;
  41356. case 2:
  41357. if (!v1Out) {
  41358. nV1 = vertices[index].clone();
  41359. nV2 = clipVertices(nV1, vertices[index + 1]);
  41360. nV3 = clipVertices(nV1, vertices[index + 2]);
  41361. result.push(nV1);
  41362. result.push(nV2);
  41363. result.push(nV3);
  41364. }
  41365. if (!v2Out) {
  41366. nV1 = vertices[index + 1].clone();
  41367. nV2 = clipVertices(nV1, vertices[index + 2]);
  41368. nV3 = clipVertices(nV1, vertices[index]);
  41369. result.push(nV1);
  41370. result.push(nV2);
  41371. result.push(nV3);
  41372. }
  41373. if (!v3Out) {
  41374. nV1 = vertices[index + 2].clone();
  41375. nV2 = clipVertices(nV1, vertices[index]);
  41376. nV3 = clipVertices(nV1, vertices[index + 1]);
  41377. result.push(nV1);
  41378. result.push(nV2);
  41379. result.push(nV3);
  41380. }
  41381. break;
  41382. case 3:
  41383. break;
  41384. }
  41385. }
  41386. return result;
  41387. };
  41388. for (var index = 0; index < indices.length; index += 3) {
  41389. var faceVertices = new Array();
  41390. faceVertices.push(extractDecalVector3(index));
  41391. faceVertices.push(extractDecalVector3(index + 1));
  41392. faceVertices.push(extractDecalVector3(index + 2));
  41393. // Clip
  41394. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  41395. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  41396. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  41397. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  41398. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  41399. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  41400. if (faceVertices.length === 0) {
  41401. continue;
  41402. }
  41403. // Add UVs and get back to world
  41404. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  41405. var vertex = faceVertices[vIndex];
  41406. //TODO check for Int32Array | Uint32Array | Uint16Array
  41407. vertexData.indices.push(currentVertexDataIndex);
  41408. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  41409. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  41410. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  41411. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  41412. currentVertexDataIndex++;
  41413. }
  41414. }
  41415. // Return mesh
  41416. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  41417. vertexData.applyToMesh(decal);
  41418. decal.position = position.clone();
  41419. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  41420. return decal;
  41421. };
  41422. // Privates
  41423. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  41424. // extrusion geometry
  41425. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  41426. var tangents = path3D.getTangents();
  41427. var normals = path3D.getNormals();
  41428. var binormals = path3D.getBinormals();
  41429. var distances = path3D.getDistances();
  41430. var angle = 0;
  41431. var returnScale = function () { return scale; };
  41432. var returnRotation = function () { return rotation; };
  41433. var rotate = custom ? rotateFunction : returnRotation;
  41434. var scl = custom ? scaleFunction : returnScale;
  41435. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  41436. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  41437. for (var i = 0; i < curve.length; i++) {
  41438. var shapePath = new Array();
  41439. var angleStep = rotate(i, distances[i]);
  41440. var scaleRatio = scl(i, distances[i]);
  41441. for (var p = 0; p < shape.length; p++) {
  41442. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  41443. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  41444. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  41445. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  41446. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  41447. shapePath[p] = rotated;
  41448. }
  41449. shapePaths[index] = shapePath;
  41450. angle += angleStep;
  41451. index++;
  41452. }
  41453. // cap
  41454. var capPath = function (shapePath) {
  41455. var pointCap = Array();
  41456. var barycenter = BABYLON.Vector3.Zero();
  41457. var i;
  41458. for (i = 0; i < shapePath.length; i++) {
  41459. barycenter.addInPlace(shapePath[i]);
  41460. }
  41461. barycenter.scaleInPlace(1.0 / shapePath.length);
  41462. for (i = 0; i < shapePath.length; i++) {
  41463. pointCap.push(barycenter);
  41464. }
  41465. return pointCap;
  41466. };
  41467. switch (cap) {
  41468. case BABYLON.Mesh.NO_CAP:
  41469. break;
  41470. case BABYLON.Mesh.CAP_START:
  41471. shapePaths[0] = capPath(shapePaths[2]);
  41472. shapePaths[1] = shapePaths[2];
  41473. break;
  41474. case BABYLON.Mesh.CAP_END:
  41475. shapePaths[index] = shapePaths[index - 1];
  41476. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41477. break;
  41478. case BABYLON.Mesh.CAP_ALL:
  41479. shapePaths[0] = capPath(shapePaths[2]);
  41480. shapePaths[1] = shapePaths[2];
  41481. shapePaths[index] = shapePaths[index - 1];
  41482. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  41483. break;
  41484. default:
  41485. break;
  41486. }
  41487. return shapePaths;
  41488. };
  41489. var path3D;
  41490. var pathArray;
  41491. if (instance) {
  41492. path3D = (instance.path3D).update(curve);
  41493. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  41494. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  41495. return instance;
  41496. }
  41497. // extruded shape creation
  41498. path3D = new BABYLON.Path3D(curve);
  41499. var newShapePaths = new Array();
  41500. cap = (cap < 0 || cap > 3) ? 0 : cap;
  41501. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  41502. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  41503. extrudedGeneric.pathArray = pathArray;
  41504. extrudedGeneric.path3D = path3D;
  41505. extrudedGeneric.cap = cap;
  41506. return extrudedGeneric;
  41507. };
  41508. return MeshBuilder;
  41509. }());
  41510. BABYLON.MeshBuilder = MeshBuilder;
  41511. })(BABYLON || (BABYLON = {}));
  41512. //# sourceMappingURL=babylon.meshBuilder.js.map
  41513. var BABYLON;
  41514. (function (BABYLON) {
  41515. var AudioEngine = (function () {
  41516. function AudioEngine() {
  41517. this._audioContext = null;
  41518. this._audioContextInitialized = false;
  41519. this.canUseWebAudio = false;
  41520. this.WarnedWebAudioUnsupported = false;
  41521. this.unlocked = false;
  41522. this.isMP3supported = false;
  41523. this.isOGGsupported = false;
  41524. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41525. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41526. this.canUseWebAudio = true;
  41527. }
  41528. var audioElem = document.createElement('audio');
  41529. try {
  41530. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41531. this.isMP3supported = true;
  41532. }
  41533. }
  41534. catch (e) {
  41535. // protect error during capability check.
  41536. }
  41537. try {
  41538. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41539. this.isOGGsupported = true;
  41540. }
  41541. }
  41542. catch (e) {
  41543. // protect error during capability check.
  41544. }
  41545. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41546. this._unlockiOSaudio();
  41547. }
  41548. else {
  41549. this.unlocked = true;
  41550. }
  41551. }
  41552. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41553. get: function () {
  41554. if (!this._audioContextInitialized) {
  41555. this._initializeAudioContext();
  41556. }
  41557. return this._audioContext;
  41558. },
  41559. enumerable: true,
  41560. configurable: true
  41561. });
  41562. AudioEngine.prototype._unlockiOSaudio = function () {
  41563. var _this = this;
  41564. var unlockaudio = function () {
  41565. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41566. var source = _this.audioContext.createBufferSource();
  41567. source.buffer = buffer;
  41568. source.connect(_this.audioContext.destination);
  41569. source.start(0);
  41570. setTimeout(function () {
  41571. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41572. _this.unlocked = true;
  41573. window.removeEventListener('touchend', unlockaudio, false);
  41574. if (_this.onAudioUnlocked) {
  41575. _this.onAudioUnlocked();
  41576. }
  41577. }
  41578. }, 0);
  41579. };
  41580. window.addEventListener('touchend', unlockaudio, false);
  41581. };
  41582. AudioEngine.prototype._initializeAudioContext = function () {
  41583. try {
  41584. if (this.canUseWebAudio) {
  41585. this._audioContext = new AudioContext();
  41586. // create a global volume gain node
  41587. this.masterGain = this._audioContext.createGain();
  41588. this.masterGain.gain.value = 1;
  41589. this.masterGain.connect(this._audioContext.destination);
  41590. this._audioContextInitialized = true;
  41591. }
  41592. }
  41593. catch (e) {
  41594. this.canUseWebAudio = false;
  41595. BABYLON.Tools.Error("Web Audio: " + e.message);
  41596. }
  41597. };
  41598. AudioEngine.prototype.dispose = function () {
  41599. if (this.canUseWebAudio && this._audioContextInitialized) {
  41600. if (this._connectedAnalyser) {
  41601. this._connectedAnalyser.stopDebugCanvas();
  41602. this._connectedAnalyser.dispose();
  41603. this.masterGain.disconnect();
  41604. this.masterGain.connect(this._audioContext.destination);
  41605. this._connectedAnalyser = null;
  41606. }
  41607. this.masterGain.gain.value = 1;
  41608. }
  41609. this.WarnedWebAudioUnsupported = false;
  41610. };
  41611. AudioEngine.prototype.getGlobalVolume = function () {
  41612. if (this.canUseWebAudio && this._audioContextInitialized) {
  41613. return this.masterGain.gain.value;
  41614. }
  41615. else {
  41616. return -1;
  41617. }
  41618. };
  41619. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41620. if (this.canUseWebAudio && this._audioContextInitialized) {
  41621. this.masterGain.gain.value = newVolume;
  41622. }
  41623. };
  41624. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41625. if (this._connectedAnalyser) {
  41626. this._connectedAnalyser.stopDebugCanvas();
  41627. }
  41628. if (this.canUseWebAudio && this._audioContextInitialized) {
  41629. this._connectedAnalyser = analyser;
  41630. this.masterGain.disconnect();
  41631. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41632. }
  41633. };
  41634. return AudioEngine;
  41635. }());
  41636. BABYLON.AudioEngine = AudioEngine;
  41637. })(BABYLON || (BABYLON = {}));
  41638. //# sourceMappingURL=babylon.audioEngine.js.map
  41639. var BABYLON;
  41640. (function (BABYLON) {
  41641. var Sound = (function () {
  41642. /**
  41643. * Create a sound and attach it to a scene
  41644. * @param name Name of your sound
  41645. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41646. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41647. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41648. */
  41649. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41650. var _this = this;
  41651. this.autoplay = false;
  41652. this.loop = false;
  41653. this.useCustomAttenuation = false;
  41654. this.spatialSound = false;
  41655. this.refDistance = 1;
  41656. this.rolloffFactor = 1;
  41657. this.maxDistance = 100;
  41658. this.distanceModel = "linear";
  41659. this._panningModel = "equalpower";
  41660. this._playbackRate = 1;
  41661. this._streaming = false;
  41662. this._startTime = 0;
  41663. this._startOffset = 0;
  41664. this._position = BABYLON.Vector3.Zero();
  41665. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41666. this._volume = 1;
  41667. this._isLoaded = false;
  41668. this._isReadyToPlay = false;
  41669. this.isPlaying = false;
  41670. this.isPaused = false;
  41671. this._isDirectional = false;
  41672. // Used if you'd like to create a directional sound.
  41673. // If not set, the sound will be omnidirectional
  41674. this._coneInnerAngle = 360;
  41675. this._coneOuterAngle = 360;
  41676. this._coneOuterGain = 0;
  41677. this._isOutputConnected = false;
  41678. this._urlType = "Unknown";
  41679. this.name = name;
  41680. this._scene = scene;
  41681. this._readyToPlayCallback = readyToPlayCallback;
  41682. // Default custom attenuation function is a linear attenuation
  41683. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41684. if (currentDistance < maxDistance) {
  41685. return currentVolume * (1 - currentDistance / maxDistance);
  41686. }
  41687. else {
  41688. return 0;
  41689. }
  41690. };
  41691. if (options) {
  41692. this.autoplay = options.autoplay || false;
  41693. this.loop = options.loop || false;
  41694. // if volume === 0, we need another way to check this option
  41695. if (options.volume !== undefined) {
  41696. this._volume = options.volume;
  41697. }
  41698. this.spatialSound = options.spatialSound || false;
  41699. this.maxDistance = options.maxDistance || 100;
  41700. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41701. this.rolloffFactor = options.rolloffFactor || 1;
  41702. this.refDistance = options.refDistance || 1;
  41703. this.distanceModel = options.distanceModel || "linear";
  41704. this._playbackRate = options.playbackRate || 1;
  41705. this._streaming = options.streaming || false;
  41706. }
  41707. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41708. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41709. this._soundGain.gain.value = this._volume;
  41710. this._inputAudioNode = this._soundGain;
  41711. this._ouputAudioNode = this._soundGain;
  41712. if (this.spatialSound) {
  41713. this._createSpatialParameters();
  41714. }
  41715. this._scene.mainSoundTrack.AddSound(this);
  41716. var validParameter = true;
  41717. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41718. if (urlOrArrayBuffer) {
  41719. if (typeof (urlOrArrayBuffer) === "string")
  41720. this._urlType = "String";
  41721. if (Array.isArray(urlOrArrayBuffer))
  41722. this._urlType = "Array";
  41723. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41724. this._urlType = "ArrayBuffer";
  41725. var urls = [];
  41726. var codecSupportedFound = false;
  41727. switch (this._urlType) {
  41728. case "ArrayBuffer":
  41729. if (urlOrArrayBuffer.byteLength > 0) {
  41730. codecSupportedFound = true;
  41731. this._soundLoaded(urlOrArrayBuffer);
  41732. }
  41733. break;
  41734. case "String":
  41735. urls.push(urlOrArrayBuffer);
  41736. case "Array":
  41737. if (urls.length === 0)
  41738. urls = urlOrArrayBuffer;
  41739. // If we found a supported format, we load it immediately and stop the loop
  41740. for (var i = 0; i < urls.length; i++) {
  41741. var url = urls[i];
  41742. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41743. codecSupportedFound = true;
  41744. }
  41745. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41746. codecSupportedFound = true;
  41747. }
  41748. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41749. codecSupportedFound = true;
  41750. }
  41751. if (codecSupportedFound) {
  41752. // Loading sound using XHR2
  41753. if (!this._streaming) {
  41754. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41755. }
  41756. else {
  41757. this._htmlAudioElement = new Audio(url);
  41758. this._htmlAudioElement.controls = false;
  41759. this._htmlAudioElement.loop = this.loop;
  41760. this._htmlAudioElement.crossOrigin = "anonymous";
  41761. this._htmlAudioElement.preload = "auto";
  41762. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41763. _this._isReadyToPlay = true;
  41764. if (_this.autoplay) {
  41765. _this.play();
  41766. }
  41767. if (_this._readyToPlayCallback) {
  41768. _this._readyToPlayCallback();
  41769. }
  41770. });
  41771. document.body.appendChild(this._htmlAudioElement);
  41772. }
  41773. break;
  41774. }
  41775. }
  41776. break;
  41777. default:
  41778. validParameter = false;
  41779. break;
  41780. }
  41781. if (!validParameter) {
  41782. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41783. }
  41784. else {
  41785. if (!codecSupportedFound) {
  41786. this._isReadyToPlay = true;
  41787. // Simulating a ready to play event to avoid breaking code path
  41788. if (this._readyToPlayCallback) {
  41789. window.setTimeout(function () {
  41790. _this._readyToPlayCallback();
  41791. }, 1000);
  41792. }
  41793. }
  41794. }
  41795. }
  41796. }
  41797. else {
  41798. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  41799. this._scene.mainSoundTrack.AddSound(this);
  41800. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  41801. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  41802. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  41803. }
  41804. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  41805. if (this._readyToPlayCallback) {
  41806. window.setTimeout(function () {
  41807. _this._readyToPlayCallback();
  41808. }, 1000);
  41809. }
  41810. }
  41811. }
  41812. Sound.prototype.dispose = function () {
  41813. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  41814. if (this.isPlaying) {
  41815. this.stop();
  41816. }
  41817. this._isReadyToPlay = false;
  41818. if (this.soundTrackId === -1) {
  41819. this._scene.mainSoundTrack.RemoveSound(this);
  41820. }
  41821. else {
  41822. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  41823. }
  41824. if (this._soundGain) {
  41825. this._soundGain.disconnect();
  41826. this._soundGain = null;
  41827. }
  41828. if (this._soundPanner) {
  41829. this._soundPanner.disconnect();
  41830. this._soundPanner = null;
  41831. }
  41832. if (this._soundSource) {
  41833. this._soundSource.disconnect();
  41834. this._soundSource = null;
  41835. }
  41836. this._audioBuffer = null;
  41837. if (this._htmlAudioElement) {
  41838. this._htmlAudioElement.pause();
  41839. this._htmlAudioElement.src = "";
  41840. document.body.removeChild(this._htmlAudioElement);
  41841. }
  41842. if (this._connectedMesh) {
  41843. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  41844. this._connectedMesh = null;
  41845. }
  41846. }
  41847. };
  41848. Sound.prototype.isReady = function () {
  41849. return this._isReadyToPlay;
  41850. };
  41851. Sound.prototype._soundLoaded = function (audioData) {
  41852. var _this = this;
  41853. this._isLoaded = true;
  41854. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  41855. _this._audioBuffer = buffer;
  41856. _this._isReadyToPlay = true;
  41857. if (_this.autoplay) {
  41858. _this.play();
  41859. }
  41860. if (_this._readyToPlayCallback) {
  41861. _this._readyToPlayCallback();
  41862. }
  41863. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  41864. };
  41865. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  41866. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41867. this._audioBuffer = audioBuffer;
  41868. this._isReadyToPlay = true;
  41869. }
  41870. };
  41871. Sound.prototype.updateOptions = function (options) {
  41872. if (options) {
  41873. this.loop = options.loop || this.loop;
  41874. this.maxDistance = options.maxDistance || this.maxDistance;
  41875. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  41876. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  41877. this.refDistance = options.refDistance || this.refDistance;
  41878. this.distanceModel = options.distanceModel || this.distanceModel;
  41879. this._playbackRate = options.playbackRate || this._playbackRate;
  41880. this._updateSpatialParameters();
  41881. if (this.isPlaying) {
  41882. if (this._streaming) {
  41883. this._htmlAudioElement.playbackRate = this._playbackRate;
  41884. }
  41885. else {
  41886. this._soundSource.playbackRate.value = this._playbackRate;
  41887. }
  41888. }
  41889. }
  41890. };
  41891. Sound.prototype._createSpatialParameters = function () {
  41892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41893. if (this._scene.headphone) {
  41894. this._panningModel = "HRTF";
  41895. }
  41896. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  41897. this._updateSpatialParameters();
  41898. this._soundPanner.connect(this._ouputAudioNode);
  41899. this._inputAudioNode = this._soundPanner;
  41900. }
  41901. };
  41902. Sound.prototype._updateSpatialParameters = function () {
  41903. if (this.spatialSound) {
  41904. if (this.useCustomAttenuation) {
  41905. // Tricks to disable in a way embedded Web Audio attenuation
  41906. this._soundPanner.distanceModel = "linear";
  41907. this._soundPanner.maxDistance = Number.MAX_VALUE;
  41908. this._soundPanner.refDistance = 1;
  41909. this._soundPanner.rolloffFactor = 1;
  41910. this._soundPanner.panningModel = this._panningModel;
  41911. }
  41912. else {
  41913. this._soundPanner.distanceModel = this.distanceModel;
  41914. this._soundPanner.maxDistance = this.maxDistance;
  41915. this._soundPanner.refDistance = this.refDistance;
  41916. this._soundPanner.rolloffFactor = this.rolloffFactor;
  41917. this._soundPanner.panningModel = this._panningModel;
  41918. }
  41919. }
  41920. };
  41921. Sound.prototype.switchPanningModelToHRTF = function () {
  41922. this._panningModel = "HRTF";
  41923. this._switchPanningModel();
  41924. };
  41925. Sound.prototype.switchPanningModelToEqualPower = function () {
  41926. this._panningModel = "equalpower";
  41927. this._switchPanningModel();
  41928. };
  41929. Sound.prototype._switchPanningModel = function () {
  41930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41931. this._soundPanner.panningModel = this._panningModel;
  41932. }
  41933. };
  41934. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  41935. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41936. if (this._isOutputConnected) {
  41937. this._ouputAudioNode.disconnect();
  41938. }
  41939. this._ouputAudioNode.connect(soundTrackAudioNode);
  41940. this._isOutputConnected = true;
  41941. }
  41942. };
  41943. /**
  41944. * Transform this sound into a directional source
  41945. * @param coneInnerAngle Size of the inner cone in degree
  41946. * @param coneOuterAngle Size of the outer cone in degree
  41947. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  41948. */
  41949. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  41950. if (coneOuterAngle < coneInnerAngle) {
  41951. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  41952. return;
  41953. }
  41954. this._coneInnerAngle = coneInnerAngle;
  41955. this._coneOuterAngle = coneOuterAngle;
  41956. this._coneOuterGain = coneOuterGain;
  41957. this._isDirectional = true;
  41958. if (this.isPlaying && this.loop) {
  41959. this.stop();
  41960. this.play();
  41961. }
  41962. };
  41963. Sound.prototype.setPosition = function (newPosition) {
  41964. this._position = newPosition;
  41965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  41966. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  41967. }
  41968. };
  41969. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  41970. this._localDirection = newLocalDirection;
  41971. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  41972. this._updateDirection();
  41973. }
  41974. };
  41975. Sound.prototype._updateDirection = function () {
  41976. var mat = this._connectedMesh.getWorldMatrix();
  41977. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  41978. direction.normalize();
  41979. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  41980. };
  41981. Sound.prototype.updateDistanceFromListener = function () {
  41982. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  41983. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  41984. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  41985. }
  41986. };
  41987. Sound.prototype.setAttenuationFunction = function (callback) {
  41988. this._customAttenuationFunction = callback;
  41989. };
  41990. /**
  41991. * Play the sound
  41992. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  41993. * @param offset (optional) Start the sound setting it at a specific time
  41994. */
  41995. Sound.prototype.play = function (time, offset) {
  41996. var _this = this;
  41997. if (this._isReadyToPlay && this._scene.audioEnabled) {
  41998. try {
  41999. if (this._startOffset < 0) {
  42000. time = -this._startOffset;
  42001. this._startOffset = 0;
  42002. }
  42003. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42004. if (!this._soundSource || !this._streamingSource) {
  42005. if (this.spatialSound) {
  42006. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42007. if (this._isDirectional) {
  42008. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42009. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42010. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42011. if (this._connectedMesh) {
  42012. this._updateDirection();
  42013. }
  42014. else {
  42015. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42016. }
  42017. }
  42018. }
  42019. }
  42020. if (this._streaming) {
  42021. if (!this._streamingSource) {
  42022. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42023. this._htmlAudioElement.onended = function () { _this._onended(); };
  42024. this._htmlAudioElement.playbackRate = this._playbackRate;
  42025. }
  42026. this._streamingSource.disconnect();
  42027. this._streamingSource.connect(this._inputAudioNode);
  42028. this._htmlAudioElement.play();
  42029. }
  42030. else {
  42031. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42032. this._soundSource.buffer = this._audioBuffer;
  42033. this._soundSource.connect(this._inputAudioNode);
  42034. this._soundSource.loop = this.loop;
  42035. this._soundSource.playbackRate.value = this._playbackRate;
  42036. this._soundSource.onended = function () { _this._onended(); };
  42037. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42038. }
  42039. this._startTime = startTime;
  42040. this.isPlaying = true;
  42041. this.isPaused = false;
  42042. }
  42043. catch (ex) {
  42044. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42045. }
  42046. }
  42047. };
  42048. Sound.prototype._onended = function () {
  42049. this.isPlaying = false;
  42050. if (this.onended) {
  42051. this.onended();
  42052. }
  42053. };
  42054. /**
  42055. * Stop the sound
  42056. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42057. */
  42058. Sound.prototype.stop = function (time) {
  42059. if (this.isPlaying) {
  42060. if (this._streaming) {
  42061. this._htmlAudioElement.pause();
  42062. // Test needed for Firefox or it will generate an Invalid State Error
  42063. if (this._htmlAudioElement.currentTime > 0) {
  42064. this._htmlAudioElement.currentTime = 0;
  42065. }
  42066. }
  42067. else {
  42068. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42069. this._soundSource.stop(stopTime);
  42070. this._soundSource.onended = null;
  42071. if (!this.isPaused) {
  42072. this._startOffset = 0;
  42073. }
  42074. }
  42075. this.isPlaying = false;
  42076. }
  42077. };
  42078. Sound.prototype.pause = function () {
  42079. if (this.isPlaying) {
  42080. this.isPaused = true;
  42081. if (this._streaming) {
  42082. this._htmlAudioElement.pause();
  42083. }
  42084. else {
  42085. this.stop(0);
  42086. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42087. }
  42088. }
  42089. };
  42090. Sound.prototype.setVolume = function (newVolume, time) {
  42091. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42092. if (time) {
  42093. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42094. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42095. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42096. }
  42097. else {
  42098. this._soundGain.gain.value = newVolume;
  42099. }
  42100. }
  42101. this._volume = newVolume;
  42102. };
  42103. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42104. this._playbackRate = newPlaybackRate;
  42105. if (this.isPlaying) {
  42106. if (this._streaming) {
  42107. this._htmlAudioElement.playbackRate = this._playbackRate;
  42108. }
  42109. else {
  42110. this._soundSource.playbackRate.value = this._playbackRate;
  42111. }
  42112. }
  42113. };
  42114. Sound.prototype.getVolume = function () {
  42115. return this._volume;
  42116. };
  42117. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42118. var _this = this;
  42119. if (this._connectedMesh) {
  42120. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42121. this._registerFunc = null;
  42122. }
  42123. this._connectedMesh = meshToConnectTo;
  42124. if (!this.spatialSound) {
  42125. this.spatialSound = true;
  42126. this._createSpatialParameters();
  42127. if (this.isPlaying && this.loop) {
  42128. this.stop();
  42129. this.play();
  42130. }
  42131. }
  42132. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42133. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42134. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42135. };
  42136. Sound.prototype.detachFromMesh = function () {
  42137. if (this._connectedMesh) {
  42138. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42139. this._registerFunc = null;
  42140. this._connectedMesh = null;
  42141. }
  42142. };
  42143. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42144. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42146. this._updateDirection();
  42147. }
  42148. };
  42149. Sound.prototype.clone = function () {
  42150. var _this = this;
  42151. if (!this._streaming) {
  42152. var setBufferAndRun = function () {
  42153. if (_this._isReadyToPlay) {
  42154. clonedSound._audioBuffer = _this.getAudioBuffer();
  42155. clonedSound._isReadyToPlay = true;
  42156. if (clonedSound.autoplay) {
  42157. clonedSound.play();
  42158. }
  42159. }
  42160. else {
  42161. window.setTimeout(setBufferAndRun, 300);
  42162. }
  42163. };
  42164. var currentOptions = {
  42165. autoplay: this.autoplay, loop: this.loop,
  42166. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42167. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42168. refDistance: this.refDistance, distanceModel: this.distanceModel
  42169. };
  42170. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42171. if (this.useCustomAttenuation) {
  42172. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42173. }
  42174. clonedSound.setPosition(this._position);
  42175. clonedSound.setPlaybackRate(this._playbackRate);
  42176. setBufferAndRun();
  42177. return clonedSound;
  42178. }
  42179. else {
  42180. return null;
  42181. }
  42182. };
  42183. Sound.prototype.getAudioBuffer = function () {
  42184. return this._audioBuffer;
  42185. };
  42186. Sound.prototype.serialize = function () {
  42187. var serializationObject = {
  42188. name: this.name,
  42189. url: this.name,
  42190. autoplay: this.autoplay,
  42191. loop: this.loop,
  42192. volume: this._volume,
  42193. spatialSound: this.spatialSound,
  42194. maxDistance: this.maxDistance,
  42195. rolloffFactor: this.rolloffFactor,
  42196. refDistance: this.refDistance,
  42197. distanceModel: this.distanceModel,
  42198. playbackRate: this._playbackRate,
  42199. panningModel: this._panningModel,
  42200. soundTrackId: this.soundTrackId
  42201. };
  42202. if (this.spatialSound) {
  42203. if (this._connectedMesh)
  42204. serializationObject.connectedMeshId = this._connectedMesh.id;
  42205. serializationObject.position = this._position.asArray();
  42206. serializationObject.refDistance = this.refDistance;
  42207. serializationObject.distanceModel = this.distanceModel;
  42208. serializationObject.isDirectional = this._isDirectional;
  42209. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42210. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42211. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42212. serializationObject.coneOuterGain = this._coneOuterGain;
  42213. }
  42214. return serializationObject;
  42215. };
  42216. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42217. var soundName = parsedSound.name;
  42218. var soundUrl;
  42219. if (parsedSound.url) {
  42220. soundUrl = rootUrl + parsedSound.url;
  42221. }
  42222. else {
  42223. soundUrl = rootUrl + soundName;
  42224. }
  42225. var options = {
  42226. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42227. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42228. rolloffFactor: parsedSound.rolloffFactor,
  42229. refDistance: parsedSound.refDistance,
  42230. distanceModel: parsedSound.distanceModel,
  42231. playbackRate: parsedSound.playbackRate
  42232. };
  42233. var newSound;
  42234. if (!sourceSound) {
  42235. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42236. scene._addPendingData(newSound);
  42237. }
  42238. else {
  42239. var setBufferAndRun = function () {
  42240. if (sourceSound._isReadyToPlay) {
  42241. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42242. newSound._isReadyToPlay = true;
  42243. if (newSound.autoplay) {
  42244. newSound.play();
  42245. }
  42246. }
  42247. else {
  42248. window.setTimeout(setBufferAndRun, 300);
  42249. }
  42250. };
  42251. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42252. setBufferAndRun();
  42253. }
  42254. if (parsedSound.position) {
  42255. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42256. newSound.setPosition(soundPosition);
  42257. }
  42258. if (parsedSound.isDirectional) {
  42259. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42260. if (parsedSound.localDirectionToMesh) {
  42261. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42262. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42263. }
  42264. }
  42265. if (parsedSound.connectedMeshId) {
  42266. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42267. if (connectedMesh) {
  42268. newSound.attachToMesh(connectedMesh);
  42269. }
  42270. }
  42271. return newSound;
  42272. };
  42273. return Sound;
  42274. }());
  42275. BABYLON.Sound = Sound;
  42276. })(BABYLON || (BABYLON = {}));
  42277. //# sourceMappingURL=babylon.sound.js.map
  42278. var BABYLON;
  42279. (function (BABYLON) {
  42280. var SoundTrack = (function () {
  42281. function SoundTrack(scene, options) {
  42282. this.id = -1;
  42283. this._isMainTrack = false;
  42284. this._isInitialized = false;
  42285. this._scene = scene;
  42286. this.soundCollection = new Array();
  42287. this._options = options;
  42288. if (!this._isMainTrack) {
  42289. this._scene.soundTracks.push(this);
  42290. this.id = this._scene.soundTracks.length - 1;
  42291. }
  42292. }
  42293. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42294. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42295. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42296. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42297. if (this._options) {
  42298. if (this._options.volume) {
  42299. this._outputAudioNode.gain.value = this._options.volume;
  42300. }
  42301. if (this._options.mainTrack) {
  42302. this._isMainTrack = this._options.mainTrack;
  42303. }
  42304. }
  42305. this._isInitialized = true;
  42306. }
  42307. };
  42308. SoundTrack.prototype.dispose = function () {
  42309. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42310. if (this._connectedAnalyser) {
  42311. this._connectedAnalyser.stopDebugCanvas();
  42312. }
  42313. while (this.soundCollection.length) {
  42314. this.soundCollection[0].dispose();
  42315. }
  42316. if (this._outputAudioNode) {
  42317. this._outputAudioNode.disconnect();
  42318. }
  42319. this._outputAudioNode = null;
  42320. }
  42321. };
  42322. SoundTrack.prototype.AddSound = function (sound) {
  42323. if (!this._isInitialized) {
  42324. this._initializeSoundTrackAudioGraph();
  42325. }
  42326. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42327. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42328. }
  42329. if (sound.soundTrackId) {
  42330. if (sound.soundTrackId === -1) {
  42331. this._scene.mainSoundTrack.RemoveSound(sound);
  42332. }
  42333. else {
  42334. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42335. }
  42336. }
  42337. this.soundCollection.push(sound);
  42338. sound.soundTrackId = this.id;
  42339. };
  42340. SoundTrack.prototype.RemoveSound = function (sound) {
  42341. var index = this.soundCollection.indexOf(sound);
  42342. if (index !== -1) {
  42343. this.soundCollection.splice(index, 1);
  42344. }
  42345. };
  42346. SoundTrack.prototype.setVolume = function (newVolume) {
  42347. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42348. this._outputAudioNode.gain.value = newVolume;
  42349. }
  42350. };
  42351. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42353. for (var i = 0; i < this.soundCollection.length; i++) {
  42354. this.soundCollection[i].switchPanningModelToHRTF();
  42355. }
  42356. }
  42357. };
  42358. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42359. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42360. for (var i = 0; i < this.soundCollection.length; i++) {
  42361. this.soundCollection[i].switchPanningModelToEqualPower();
  42362. }
  42363. }
  42364. };
  42365. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42366. if (this._connectedAnalyser) {
  42367. this._connectedAnalyser.stopDebugCanvas();
  42368. }
  42369. this._connectedAnalyser = analyser;
  42370. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42371. this._outputAudioNode.disconnect();
  42372. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42373. }
  42374. };
  42375. return SoundTrack;
  42376. }());
  42377. BABYLON.SoundTrack = SoundTrack;
  42378. })(BABYLON || (BABYLON = {}));
  42379. //# sourceMappingURL=babylon.soundtrack.js.map
  42380. var BABYLON;
  42381. (function (BABYLON) {
  42382. var Analyser = (function () {
  42383. function Analyser(scene) {
  42384. this.SMOOTHING = 0.75;
  42385. this.FFT_SIZE = 512;
  42386. this.BARGRAPHAMPLITUDE = 256;
  42387. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  42388. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  42389. this._scene = scene;
  42390. this._audioEngine = BABYLON.Engine.audioEngine;
  42391. if (this._audioEngine.canUseWebAudio) {
  42392. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  42393. this._webAudioAnalyser.minDecibels = -140;
  42394. this._webAudioAnalyser.maxDecibels = 0;
  42395. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42396. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  42397. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  42398. }
  42399. }
  42400. Analyser.prototype.getFrequencyBinCount = function () {
  42401. if (this._audioEngine.canUseWebAudio) {
  42402. return this._webAudioAnalyser.frequencyBinCount;
  42403. }
  42404. else {
  42405. return 0;
  42406. }
  42407. };
  42408. Analyser.prototype.getByteFrequencyData = function () {
  42409. if (this._audioEngine.canUseWebAudio) {
  42410. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42411. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42412. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  42413. }
  42414. return this._byteFreqs;
  42415. };
  42416. Analyser.prototype.getByteTimeDomainData = function () {
  42417. if (this._audioEngine.canUseWebAudio) {
  42418. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42419. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42420. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  42421. }
  42422. return this._byteTime;
  42423. };
  42424. Analyser.prototype.getFloatFrequencyData = function () {
  42425. if (this._audioEngine.canUseWebAudio) {
  42426. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  42427. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  42428. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  42429. }
  42430. return this._floatFreqs;
  42431. };
  42432. Analyser.prototype.drawDebugCanvas = function () {
  42433. var _this = this;
  42434. if (this._audioEngine.canUseWebAudio) {
  42435. if (!this._debugCanvas) {
  42436. this._debugCanvas = document.createElement("canvas");
  42437. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  42438. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  42439. this._debugCanvas.style.position = "absolute";
  42440. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  42441. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  42442. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  42443. document.body.appendChild(this._debugCanvas);
  42444. this._registerFunc = function () {
  42445. _this.drawDebugCanvas();
  42446. };
  42447. this._scene.registerBeforeRender(this._registerFunc);
  42448. }
  42449. if (this._registerFunc) {
  42450. var workingArray = this.getByteFrequencyData();
  42451. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  42452. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  42453. // Draw the frequency domain chart.
  42454. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  42455. var value = workingArray[i];
  42456. var percent = value / this.BARGRAPHAMPLITUDE;
  42457. var height = this.DEBUGCANVASSIZE.height * percent;
  42458. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  42459. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  42460. var hue = i / this.getFrequencyBinCount() * 360;
  42461. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  42462. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  42463. }
  42464. }
  42465. }
  42466. };
  42467. Analyser.prototype.stopDebugCanvas = function () {
  42468. if (this._debugCanvas) {
  42469. this._scene.unregisterBeforeRender(this._registerFunc);
  42470. this._registerFunc = null;
  42471. document.body.removeChild(this._debugCanvas);
  42472. this._debugCanvas = null;
  42473. this._debugCanvasContext = null;
  42474. }
  42475. };
  42476. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  42477. if (this._audioEngine.canUseWebAudio) {
  42478. inputAudioNode.connect(this._webAudioAnalyser);
  42479. this._webAudioAnalyser.connect(outputAudioNode);
  42480. }
  42481. };
  42482. Analyser.prototype.dispose = function () {
  42483. if (this._audioEngine.canUseWebAudio) {
  42484. this._webAudioAnalyser.disconnect();
  42485. }
  42486. };
  42487. return Analyser;
  42488. }());
  42489. BABYLON.Analyser = Analyser;
  42490. })(BABYLON || (BABYLON = {}));
  42491. //# sourceMappingURL=babylon.analyser.js.map
  42492. var BABYLON;
  42493. (function (BABYLON) {
  42494. var CubeTexture = (function (_super) {
  42495. __extends(CubeTexture, _super);
  42496. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  42497. if (onLoad === void 0) { onLoad = null; }
  42498. if (onError === void 0) { onError = null; }
  42499. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  42500. var _this = _super.call(this, scene) || this;
  42501. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  42502. _this.name = rootUrl;
  42503. _this.url = rootUrl;
  42504. _this._noMipmap = noMipmap;
  42505. _this.hasAlpha = false;
  42506. _this._format = format;
  42507. if (!rootUrl && !files) {
  42508. return _this;
  42509. }
  42510. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  42511. if (!files) {
  42512. if (!extensions) {
  42513. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  42514. }
  42515. files = [];
  42516. for (var index = 0; index < extensions.length; index++) {
  42517. files.push(rootUrl + extensions[index]);
  42518. }
  42519. _this._extensions = extensions;
  42520. }
  42521. _this._files = files;
  42522. if (!_this._texture) {
  42523. if (!scene.useDelayedTextureLoading) {
  42524. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  42525. }
  42526. else {
  42527. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  42528. }
  42529. }
  42530. else if (onLoad) {
  42531. if (_this._texture.isReady) {
  42532. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  42533. }
  42534. else {
  42535. _this._texture.onLoadedCallbacks.push(onLoad);
  42536. }
  42537. }
  42538. _this.isCube = true;
  42539. _this._textureMatrix = BABYLON.Matrix.Identity();
  42540. return _this;
  42541. }
  42542. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  42543. return new CubeTexture("", scene, null, noMipmap, files);
  42544. };
  42545. // Methods
  42546. CubeTexture.prototype.delayLoad = function () {
  42547. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  42548. return;
  42549. }
  42550. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  42551. this._texture = this._getFromCache(this.url, this._noMipmap);
  42552. if (!this._texture) {
  42553. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  42554. }
  42555. };
  42556. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  42557. return this._textureMatrix;
  42558. };
  42559. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  42560. var texture = BABYLON.SerializationHelper.Parse(function () {
  42561. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  42562. }, parsedTexture, scene);
  42563. // Animations
  42564. if (parsedTexture.animations) {
  42565. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  42566. var parsedAnimation = parsedTexture.animations[animationIndex];
  42567. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  42568. }
  42569. }
  42570. return texture;
  42571. };
  42572. CubeTexture.prototype.clone = function () {
  42573. var _this = this;
  42574. return BABYLON.SerializationHelper.Clone(function () {
  42575. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  42576. }, this);
  42577. };
  42578. return CubeTexture;
  42579. }(BABYLON.BaseTexture));
  42580. BABYLON.CubeTexture = CubeTexture;
  42581. })(BABYLON || (BABYLON = {}));
  42582. //# sourceMappingURL=babylon.cubeTexture.js.map
  42583. var BABYLON;
  42584. (function (BABYLON) {
  42585. var RenderTargetTexture = (function (_super) {
  42586. __extends(RenderTargetTexture, _super);
  42587. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  42588. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  42589. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42590. if (isCube === void 0) { isCube = false; }
  42591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42592. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  42593. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  42594. if (isMulti === void 0) { isMulti = false; }
  42595. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  42596. _this.isCube = isCube;
  42597. /**
  42598. * Use this list to define the list of mesh you want to render.
  42599. */
  42600. _this.renderList = new Array();
  42601. _this.renderParticles = true;
  42602. _this.renderSprites = false;
  42603. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  42604. // Events
  42605. /**
  42606. * An event triggered when the texture is unbind.
  42607. * @type {BABYLON.Observable}
  42608. */
  42609. _this.onAfterUnbindObservable = new BABYLON.Observable();
  42610. /**
  42611. * An event triggered before rendering the texture
  42612. * @type {BABYLON.Observable}
  42613. */
  42614. _this.onBeforeRenderObservable = new BABYLON.Observable();
  42615. /**
  42616. * An event triggered after rendering the texture
  42617. * @type {BABYLON.Observable}
  42618. */
  42619. _this.onAfterRenderObservable = new BABYLON.Observable();
  42620. /**
  42621. * An event triggered after the texture clear
  42622. * @type {BABYLON.Observable}
  42623. */
  42624. _this.onClearObservable = new BABYLON.Observable();
  42625. _this._currentRefreshId = -1;
  42626. _this._refreshRate = 1;
  42627. _this._samples = 1;
  42628. _this.name = name;
  42629. _this.isRenderTarget = true;
  42630. _this._size = size;
  42631. _this._generateMipMaps = generateMipMaps;
  42632. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  42633. // Rendering groups
  42634. _this._renderingManager = new BABYLON.RenderingManager(scene);
  42635. if (isMulti) {
  42636. return _this;
  42637. }
  42638. _this._renderTargetOptions = {
  42639. generateMipMaps: generateMipMaps,
  42640. type: type,
  42641. samplingMode: samplingMode,
  42642. generateDepthBuffer: generateDepthBuffer,
  42643. generateStencilBuffer: generateStencilBuffer
  42644. };
  42645. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  42646. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42647. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42648. }
  42649. if (isCube) {
  42650. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  42651. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  42652. _this._textureMatrix = BABYLON.Matrix.Identity();
  42653. }
  42654. else {
  42655. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  42656. }
  42657. return _this;
  42658. }
  42659. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  42660. get: function () {
  42661. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  42662. },
  42663. enumerable: true,
  42664. configurable: true
  42665. });
  42666. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  42667. get: function () {
  42668. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  42669. },
  42670. enumerable: true,
  42671. configurable: true
  42672. });
  42673. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  42674. get: function () {
  42675. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  42676. },
  42677. enumerable: true,
  42678. configurable: true
  42679. });
  42680. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  42681. set: function (callback) {
  42682. if (this._onAfterUnbindObserver) {
  42683. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  42684. }
  42685. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  42686. },
  42687. enumerable: true,
  42688. configurable: true
  42689. });
  42690. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  42691. set: function (callback) {
  42692. if (this._onBeforeRenderObserver) {
  42693. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  42694. }
  42695. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  42696. },
  42697. enumerable: true,
  42698. configurable: true
  42699. });
  42700. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  42701. set: function (callback) {
  42702. if (this._onAfterRenderObserver) {
  42703. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  42704. }
  42705. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  42706. },
  42707. enumerable: true,
  42708. configurable: true
  42709. });
  42710. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  42711. set: function (callback) {
  42712. if (this._onClearObserver) {
  42713. this.onClearObservable.remove(this._onClearObserver);
  42714. }
  42715. this._onClearObserver = this.onClearObservable.add(callback);
  42716. },
  42717. enumerable: true,
  42718. configurable: true
  42719. });
  42720. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  42721. get: function () {
  42722. return this._renderTargetOptions;
  42723. },
  42724. enumerable: true,
  42725. configurable: true
  42726. });
  42727. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  42728. get: function () {
  42729. return this._samples;
  42730. },
  42731. set: function (value) {
  42732. if (this._samples === value) {
  42733. return;
  42734. }
  42735. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  42741. this._currentRefreshId = -1;
  42742. };
  42743. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  42744. get: function () {
  42745. return this._refreshRate;
  42746. },
  42747. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  42748. set: function (value) {
  42749. this._refreshRate = value;
  42750. this.resetRefreshCounter();
  42751. },
  42752. enumerable: true,
  42753. configurable: true
  42754. });
  42755. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  42756. if (!this._postProcessManager) {
  42757. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  42758. this._postProcesses = new Array();
  42759. }
  42760. this._postProcesses.push(postProcess);
  42761. this._postProcesses[0].autoClear = false;
  42762. };
  42763. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  42764. if (!this._postProcesses) {
  42765. return;
  42766. }
  42767. if (dispose) {
  42768. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  42769. var postProcess = _a[_i];
  42770. postProcess.dispose();
  42771. postProcess = null;
  42772. }
  42773. }
  42774. this._postProcesses = [];
  42775. };
  42776. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  42777. if (!this._postProcesses) {
  42778. return;
  42779. }
  42780. var index = this._postProcesses.indexOf(postProcess);
  42781. if (index === -1) {
  42782. return;
  42783. }
  42784. this._postProcesses.splice(index, 1);
  42785. if (this._postProcesses.length > 0) {
  42786. this._postProcesses[0].autoClear = false;
  42787. }
  42788. };
  42789. RenderTargetTexture.prototype._shouldRender = function () {
  42790. if (this._currentRefreshId === -1) {
  42791. this._currentRefreshId = 1;
  42792. return true;
  42793. }
  42794. if (this.refreshRate === this._currentRefreshId) {
  42795. this._currentRefreshId = 1;
  42796. return true;
  42797. }
  42798. this._currentRefreshId++;
  42799. return false;
  42800. };
  42801. RenderTargetTexture.prototype.isReady = function () {
  42802. if (!this.getScene().renderTargetsEnabled) {
  42803. return false;
  42804. }
  42805. return _super.prototype.isReady.call(this);
  42806. };
  42807. RenderTargetTexture.prototype.getRenderSize = function () {
  42808. return this._size;
  42809. };
  42810. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  42811. get: function () {
  42812. return true;
  42813. },
  42814. enumerable: true,
  42815. configurable: true
  42816. });
  42817. RenderTargetTexture.prototype.scale = function (ratio) {
  42818. var newSize = this._size * ratio;
  42819. this.resize(newSize);
  42820. };
  42821. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  42822. if (this.isCube) {
  42823. return this._textureMatrix;
  42824. }
  42825. return _super.prototype.getReflectionTextureMatrix.call(this);
  42826. };
  42827. RenderTargetTexture.prototype.resize = function (size) {
  42828. this.releaseInternalTexture();
  42829. if (this.isCube) {
  42830. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  42831. }
  42832. else {
  42833. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  42834. }
  42835. };
  42836. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  42837. var scene = this.getScene();
  42838. var engine = scene.getEngine();
  42839. if (this.useCameraPostProcesses !== undefined) {
  42840. useCameraPostProcess = this.useCameraPostProcesses;
  42841. }
  42842. if (this._waitingRenderList) {
  42843. this.renderList = [];
  42844. for (var index = 0; index < this._waitingRenderList.length; index++) {
  42845. var id = this._waitingRenderList[index];
  42846. this.renderList.push(scene.getMeshByID(id));
  42847. }
  42848. delete this._waitingRenderList;
  42849. }
  42850. // Is predicate defined?
  42851. if (this.renderListPredicate) {
  42852. this.renderList.splice(0); // Clear previous renderList
  42853. var sceneMeshes = this.getScene().meshes;
  42854. for (var index = 0; index < sceneMeshes.length; index++) {
  42855. var mesh = sceneMeshes[index];
  42856. if (this.renderListPredicate(mesh)) {
  42857. this.renderList.push(mesh);
  42858. }
  42859. }
  42860. }
  42861. if (this.renderList && this.renderList.length === 0) {
  42862. return;
  42863. }
  42864. // Set custom projection.
  42865. // Needs to be before binding to prevent changing the aspect ratio.
  42866. var camera;
  42867. if (this.activeCamera) {
  42868. camera = this.activeCamera;
  42869. engine.setViewport(this.activeCamera.viewport);
  42870. if (this.activeCamera !== scene.activeCamera) {
  42871. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  42872. }
  42873. }
  42874. else {
  42875. camera = scene.activeCamera;
  42876. engine.setViewport(scene.activeCamera.viewport);
  42877. }
  42878. // Prepare renderingManager
  42879. this._renderingManager.reset();
  42880. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  42881. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  42882. var sceneRenderId = scene.getRenderId();
  42883. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  42884. var mesh = currentRenderList[meshIndex];
  42885. if (mesh) {
  42886. if (!mesh.isReady()) {
  42887. // Reset _currentRefreshId
  42888. this.resetRefreshCounter();
  42889. continue;
  42890. }
  42891. mesh._preActivateForIntermediateRendering(sceneRenderId);
  42892. var isMasked = void 0;
  42893. if (!this.renderList) {
  42894. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  42895. }
  42896. else {
  42897. isMasked = false;
  42898. }
  42899. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  42900. mesh._activate(sceneRenderId);
  42901. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42902. var subMesh = mesh.subMeshes[subIndex];
  42903. scene._activeIndices.addCount(subMesh.indexCount, false);
  42904. this._renderingManager.dispatch(subMesh);
  42905. }
  42906. }
  42907. }
  42908. }
  42909. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  42910. var particleSystem = scene.particleSystems[particleIndex];
  42911. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  42912. continue;
  42913. }
  42914. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  42915. this._renderingManager.dispatchParticles(particleSystem);
  42916. }
  42917. }
  42918. if (this.isCube) {
  42919. for (var face = 0; face < 6; face++) {
  42920. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42921. scene.incrementRenderId();
  42922. scene.resetCachedMaterial();
  42923. }
  42924. }
  42925. else {
  42926. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  42927. }
  42928. this.onAfterUnbindObservable.notifyObservers(this);
  42929. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  42930. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  42931. }
  42932. engine.setViewport(scene.activeCamera.viewport);
  42933. scene.resetCachedMaterial();
  42934. };
  42935. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  42936. var _this = this;
  42937. var scene = this.getScene();
  42938. var engine = scene.getEngine();
  42939. // Bind
  42940. if (this._postProcessManager) {
  42941. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  42942. }
  42943. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  42944. if (this.isCube) {
  42945. engine.bindFramebuffer(this._texture, faceIndex);
  42946. }
  42947. else {
  42948. engine.bindFramebuffer(this._texture);
  42949. }
  42950. }
  42951. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  42952. // Clear
  42953. if (this.onClearObservable.hasObservers()) {
  42954. this.onClearObservable.notifyObservers(engine);
  42955. }
  42956. else {
  42957. engine.clear(scene.clearColor, true, true, true);
  42958. }
  42959. if (!this._doNotChangeAspectRatio) {
  42960. scene.updateTransformMatrix(true);
  42961. }
  42962. // Render
  42963. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  42964. if (this._postProcessManager) {
  42965. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  42966. }
  42967. else if (useCameraPostProcess) {
  42968. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  42969. }
  42970. if (!this._doNotChangeAspectRatio) {
  42971. scene.updateTransformMatrix(true);
  42972. }
  42973. // Dump ?
  42974. if (dumpForDebug) {
  42975. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  42976. }
  42977. // Unbind
  42978. if (!this.isCube || faceIndex === 5) {
  42979. if (this.isCube) {
  42980. if (faceIndex === 5) {
  42981. engine.generateMipMapsForCubemap(this._texture);
  42982. }
  42983. }
  42984. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  42985. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  42986. });
  42987. }
  42988. else {
  42989. this.onAfterRenderObservable.notifyObservers(faceIndex);
  42990. }
  42991. };
  42992. /**
  42993. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  42994. * This allowed control for front to back rendering or reversly depending of the special needs.
  42995. *
  42996. * @param renderingGroupId The rendering group id corresponding to its index
  42997. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  42998. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  42999. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  43000. */
  43001. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  43002. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  43003. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  43004. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  43005. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  43006. };
  43007. /**
  43008. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  43009. *
  43010. * @param renderingGroupId The rendering group id corresponding to its index
  43011. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  43012. */
  43013. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  43014. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  43015. };
  43016. RenderTargetTexture.prototype.clone = function () {
  43017. var textureSize = this.getSize();
  43018. 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);
  43019. // Base texture
  43020. newTexture.hasAlpha = this.hasAlpha;
  43021. newTexture.level = this.level;
  43022. // RenderTarget Texture
  43023. newTexture.coordinatesMode = this.coordinatesMode;
  43024. newTexture.renderList = this.renderList.slice(0);
  43025. return newTexture;
  43026. };
  43027. RenderTargetTexture.prototype.serialize = function () {
  43028. if (!this.name) {
  43029. return null;
  43030. }
  43031. var serializationObject = _super.prototype.serialize.call(this);
  43032. serializationObject.renderTargetSize = this.getRenderSize();
  43033. serializationObject.renderList = [];
  43034. for (var index = 0; index < this.renderList.length; index++) {
  43035. serializationObject.renderList.push(this.renderList[index].id);
  43036. }
  43037. return serializationObject;
  43038. };
  43039. RenderTargetTexture.prototype.dispose = function () {
  43040. if (this._postProcessManager) {
  43041. this._postProcessManager.dispose();
  43042. this._postProcessManager = null;
  43043. }
  43044. this.clearPostProcesses(true);
  43045. _super.prototype.dispose.call(this);
  43046. };
  43047. return RenderTargetTexture;
  43048. }(BABYLON.Texture));
  43049. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  43050. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  43051. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  43052. BABYLON.RenderTargetTexture = RenderTargetTexture;
  43053. })(BABYLON || (BABYLON = {}));
  43054. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  43055. var BABYLON;
  43056. (function (BABYLON) {
  43057. ;
  43058. var MultiRenderTarget = (function (_super) {
  43059. __extends(MultiRenderTarget, _super);
  43060. function MultiRenderTarget(name, size, count, scene, options) {
  43061. var _this = this;
  43062. options = options || {};
  43063. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  43064. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  43065. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  43066. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  43067. if (!_this.isSupported) {
  43068. _this.dispose();
  43069. return;
  43070. }
  43071. var types = [];
  43072. var samplingModes = [];
  43073. for (var i = 0; i < count; i++) {
  43074. if (options.types && options.types[i]) {
  43075. types.push(options.types[i]);
  43076. }
  43077. else {
  43078. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  43079. }
  43080. if (options.samplingModes && options.samplingModes[i]) {
  43081. samplingModes.push(options.samplingModes[i]);
  43082. }
  43083. else {
  43084. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43085. }
  43086. }
  43087. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  43088. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  43089. _this._count = count;
  43090. _this._size = size;
  43091. _this._multiRenderTargetOptions = {
  43092. samplingModes: samplingModes,
  43093. generateMipMaps: generateMipMaps,
  43094. generateDepthBuffer: generateDepthBuffer,
  43095. generateStencilBuffer: generateStencilBuffer,
  43096. generateDepthTexture: generateDepthTexture,
  43097. types: types,
  43098. textureCount: count
  43099. };
  43100. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  43101. _this._createInternalTextures();
  43102. return _this;
  43103. }
  43104. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  43105. get: function () {
  43106. var engine = this.getScene().getEngine();
  43107. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  43108. },
  43109. enumerable: true,
  43110. configurable: true
  43111. });
  43112. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  43113. get: function () {
  43114. return this._textures;
  43115. },
  43116. enumerable: true,
  43117. configurable: true
  43118. });
  43119. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  43120. get: function () {
  43121. return this._textures[this._textures.length - 1];
  43122. },
  43123. enumerable: true,
  43124. configurable: true
  43125. });
  43126. MultiRenderTarget.prototype._createInternalTextures = function () {
  43127. this._textures = [];
  43128. for (var i = 0; i < this._webGLTextures.length; i++) {
  43129. var texture = new BABYLON.Texture(null, this.getScene());
  43130. texture._texture = this._webGLTextures[i];
  43131. this._textures.push(texture);
  43132. }
  43133. // Keeps references to frame buffer and stencil/depth buffer
  43134. this._texture = this._webGLTextures[0];
  43135. };
  43136. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  43137. get: function () {
  43138. return this._samples;
  43139. },
  43140. set: function (value) {
  43141. if (this._samples === value) {
  43142. return;
  43143. }
  43144. for (var i = 0; i < this._webGLTextures.length; i++) {
  43145. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  43146. }
  43147. },
  43148. enumerable: true,
  43149. configurable: true
  43150. });
  43151. MultiRenderTarget.prototype.resize = function (size) {
  43152. this.releaseInternalTextures();
  43153. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  43154. this._createInternalTextures();
  43155. };
  43156. MultiRenderTarget.prototype.dispose = function () {
  43157. this.releaseInternalTextures();
  43158. _super.prototype.dispose.call(this);
  43159. };
  43160. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  43161. if (!this._webGLTextures) {
  43162. return;
  43163. }
  43164. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  43165. if (this._webGLTextures[i] !== undefined) {
  43166. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  43167. this._webGLTextures.splice(i, 1);
  43168. }
  43169. }
  43170. };
  43171. return MultiRenderTarget;
  43172. }(BABYLON.RenderTargetTexture));
  43173. BABYLON.MultiRenderTarget = MultiRenderTarget;
  43174. })(BABYLON || (BABYLON = {}));
  43175. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  43176. /// <reference path="babylon.renderTargetTexture.ts" />
  43177. var BABYLON;
  43178. (function (BABYLON) {
  43179. var MirrorTexture = (function (_super) {
  43180. __extends(MirrorTexture, _super);
  43181. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  43182. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43183. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43184. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  43185. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  43186. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  43187. _this._transformMatrix = BABYLON.Matrix.Zero();
  43188. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  43189. _this._blurKernelX = 0;
  43190. _this._blurKernelY = 0;
  43191. _this._blurRatio = 1.0;
  43192. _this.onBeforeRenderObservable.add(function () {
  43193. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  43194. _this._savedViewMatrix = scene.getViewMatrix();
  43195. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  43196. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  43197. scene.clipPlane = _this.mirrorPlane;
  43198. scene.getEngine().cullBackFaces = false;
  43199. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  43200. });
  43201. _this.onAfterRenderObservable.add(function () {
  43202. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  43203. scene.getEngine().cullBackFaces = true;
  43204. scene._mirroredCameraPosition = null;
  43205. delete scene.clipPlane;
  43206. });
  43207. return _this;
  43208. }
  43209. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  43210. get: function () {
  43211. return this._blurRatio;
  43212. },
  43213. set: function (value) {
  43214. if (this._blurRatio === value) {
  43215. return;
  43216. }
  43217. this._blurRatio = value;
  43218. this._preparePostProcesses();
  43219. },
  43220. enumerable: true,
  43221. configurable: true
  43222. });
  43223. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  43224. set: function (value) {
  43225. this.blurKernelX = value;
  43226. this.blurKernelY = value;
  43227. },
  43228. enumerable: true,
  43229. configurable: true
  43230. });
  43231. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  43232. get: function () {
  43233. return this._blurKernelX;
  43234. },
  43235. set: function (value) {
  43236. if (this._blurKernelX === value) {
  43237. return;
  43238. }
  43239. this._blurKernelX = value;
  43240. this._preparePostProcesses();
  43241. },
  43242. enumerable: true,
  43243. configurable: true
  43244. });
  43245. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  43246. get: function () {
  43247. return this._blurKernelY;
  43248. },
  43249. set: function (value) {
  43250. if (this._blurKernelY === value) {
  43251. return;
  43252. }
  43253. this._blurKernelY = value;
  43254. this._preparePostProcesses();
  43255. },
  43256. enumerable: true,
  43257. configurable: true
  43258. });
  43259. MirrorTexture.prototype._preparePostProcesses = function () {
  43260. this.clearPostProcesses(true);
  43261. if (this._blurKernelX && this._blurKernelY) {
  43262. var engine = this.getScene().getEngine();
  43263. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  43264. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  43265. this._blurX.autoClear = false;
  43266. if (this._blurRatio === 1) {
  43267. this._blurX.outputTexture = this._texture;
  43268. }
  43269. else {
  43270. this._blurX.alwaysForcePOT = true;
  43271. }
  43272. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  43273. this._blurY.autoClear = false;
  43274. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  43275. this.addPostProcess(this._blurX);
  43276. this.addPostProcess(this._blurY);
  43277. }
  43278. };
  43279. MirrorTexture.prototype.clone = function () {
  43280. var textureSize = this.getSize();
  43281. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  43282. // Base texture
  43283. newTexture.hasAlpha = this.hasAlpha;
  43284. newTexture.level = this.level;
  43285. // Mirror Texture
  43286. newTexture.mirrorPlane = this.mirrorPlane.clone();
  43287. newTexture.renderList = this.renderList.slice(0);
  43288. return newTexture;
  43289. };
  43290. MirrorTexture.prototype.serialize = function () {
  43291. if (!this.name) {
  43292. return null;
  43293. }
  43294. var serializationObject = _super.prototype.serialize.call(this);
  43295. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  43296. return serializationObject;
  43297. };
  43298. return MirrorTexture;
  43299. }(BABYLON.RenderTargetTexture));
  43300. BABYLON.MirrorTexture = MirrorTexture;
  43301. })(BABYLON || (BABYLON = {}));
  43302. //# sourceMappingURL=babylon.mirrorTexture.js.map
  43303. /// <reference path="babylon.renderTargetTexture.ts" />
  43304. var BABYLON;
  43305. (function (BABYLON) {
  43306. /**
  43307. * Creates a refraction texture used by refraction channel of the standard material.
  43308. * @param name the texture name
  43309. * @param size size of the underlying texture
  43310. * @param scene root scene
  43311. */
  43312. var RefractionTexture = (function (_super) {
  43313. __extends(RefractionTexture, _super);
  43314. function RefractionTexture(name, size, scene, generateMipMaps) {
  43315. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  43316. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  43317. _this.depth = 2.0;
  43318. _this.onBeforeRenderObservable.add(function () {
  43319. scene.clipPlane = _this.refractionPlane;
  43320. });
  43321. _this.onAfterRenderObservable.add(function () {
  43322. delete scene.clipPlane;
  43323. });
  43324. return _this;
  43325. }
  43326. RefractionTexture.prototype.clone = function () {
  43327. var textureSize = this.getSize();
  43328. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  43329. // Base texture
  43330. newTexture.hasAlpha = this.hasAlpha;
  43331. newTexture.level = this.level;
  43332. // Refraction Texture
  43333. newTexture.refractionPlane = this.refractionPlane.clone();
  43334. newTexture.renderList = this.renderList.slice(0);
  43335. newTexture.depth = this.depth;
  43336. return newTexture;
  43337. };
  43338. RefractionTexture.prototype.serialize = function () {
  43339. if (!this.name) {
  43340. return null;
  43341. }
  43342. var serializationObject = _super.prototype.serialize.call(this);
  43343. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  43344. serializationObject.depth = this.depth;
  43345. return serializationObject;
  43346. };
  43347. return RefractionTexture;
  43348. }(BABYLON.RenderTargetTexture));
  43349. BABYLON.RefractionTexture = RefractionTexture;
  43350. })(BABYLON || (BABYLON = {}));
  43351. //# sourceMappingURL=babylon.refractionTexture.js.map
  43352. /// <reference path="babylon.texture.ts" />
  43353. var BABYLON;
  43354. (function (BABYLON) {
  43355. var DynamicTexture = (function (_super) {
  43356. __extends(DynamicTexture, _super);
  43357. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  43358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43359. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  43360. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  43361. _this.name = name;
  43362. var engine = _this.getScene().getEngine();
  43363. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43364. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43365. _this._generateMipMaps = generateMipMaps;
  43366. if (options.getContext) {
  43367. _this._canvas = options;
  43368. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43369. }
  43370. else {
  43371. _this._canvas = document.createElement("canvas");
  43372. if (options.width) {
  43373. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  43374. }
  43375. else {
  43376. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  43377. }
  43378. }
  43379. var textureSize = _this.getSize();
  43380. _this._canvas.width = textureSize.width;
  43381. _this._canvas.height = textureSize.height;
  43382. _this._context = _this._canvas.getContext("2d");
  43383. return _this;
  43384. }
  43385. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  43386. get: function () {
  43387. return true;
  43388. },
  43389. enumerable: true,
  43390. configurable: true
  43391. });
  43392. DynamicTexture.prototype._recreate = function (textureSize) {
  43393. this._canvas.width = textureSize.width;
  43394. this._canvas.height = textureSize.height;
  43395. this.releaseInternalTexture();
  43396. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  43397. };
  43398. DynamicTexture.prototype.scale = function (ratio) {
  43399. var textureSize = this.getSize();
  43400. textureSize.width *= ratio;
  43401. textureSize.height *= ratio;
  43402. this._recreate(textureSize);
  43403. };
  43404. DynamicTexture.prototype.scaleTo = function (width, height) {
  43405. var textureSize = this.getSize();
  43406. textureSize.width = width;
  43407. textureSize.height = height;
  43408. this._recreate(textureSize);
  43409. };
  43410. DynamicTexture.prototype.getContext = function () {
  43411. return this._context;
  43412. };
  43413. DynamicTexture.prototype.clear = function () {
  43414. var size = this.getSize();
  43415. this._context.fillRect(0, 0, size.width, size.height);
  43416. };
  43417. DynamicTexture.prototype.update = function (invertY) {
  43418. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  43419. };
  43420. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  43421. if (update === void 0) { update = true; }
  43422. var size = this.getSize();
  43423. if (clearColor) {
  43424. this._context.fillStyle = clearColor;
  43425. this._context.fillRect(0, 0, size.width, size.height);
  43426. }
  43427. this._context.font = font;
  43428. if (x === null || x === undefined) {
  43429. var textSize = this._context.measureText(text);
  43430. x = (size.width - textSize.width) / 2;
  43431. }
  43432. if (y === null || y === undefined) {
  43433. var fontSize = parseInt((font.replace(/\D/g, '')));
  43434. ;
  43435. y = (size.height / 2) + (fontSize / 3.65);
  43436. }
  43437. this._context.fillStyle = color;
  43438. this._context.fillText(text, x, y);
  43439. if (update) {
  43440. this.update(invertY);
  43441. }
  43442. };
  43443. DynamicTexture.prototype.clone = function () {
  43444. var textureSize = this.getSize();
  43445. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  43446. // Base texture
  43447. newTexture.hasAlpha = this.hasAlpha;
  43448. newTexture.level = this.level;
  43449. // Dynamic Texture
  43450. newTexture.wrapU = this.wrapU;
  43451. newTexture.wrapV = this.wrapV;
  43452. return newTexture;
  43453. };
  43454. return DynamicTexture;
  43455. }(BABYLON.Texture));
  43456. BABYLON.DynamicTexture = DynamicTexture;
  43457. })(BABYLON || (BABYLON = {}));
  43458. //# sourceMappingURL=babylon.dynamicTexture.js.map
  43459. var BABYLON;
  43460. (function (BABYLON) {
  43461. var VideoTexture = (function (_super) {
  43462. __extends(VideoTexture, _super);
  43463. /**
  43464. * Creates a video texture.
  43465. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  43466. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  43467. * @param {BABYLON.Scene} scene is obviously the current scene.
  43468. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  43469. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  43470. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  43471. */
  43472. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  43473. if (generateMipMaps === void 0) { generateMipMaps = false; }
  43474. if (invertY === void 0) { invertY = false; }
  43475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43476. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43477. _this._autoLaunch = true;
  43478. var urls;
  43479. _this.name = name;
  43480. if (urlsOrVideo instanceof HTMLVideoElement) {
  43481. _this.video = urlsOrVideo;
  43482. }
  43483. else {
  43484. urls = urlsOrVideo;
  43485. _this.video = document.createElement("video");
  43486. _this.video.autoplay = false;
  43487. _this.video.loop = true;
  43488. }
  43489. _this._generateMipMaps = generateMipMaps;
  43490. _this._samplingMode = samplingMode;
  43491. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  43492. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  43493. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  43494. }
  43495. else {
  43496. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43497. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43498. _this._generateMipMaps = false;
  43499. }
  43500. if (urls) {
  43501. _this.video.addEventListener("canplay", function () {
  43502. _this._createTexture();
  43503. });
  43504. urls.forEach(function (url) {
  43505. var source = document.createElement("source");
  43506. source.src = url;
  43507. _this.video.appendChild(source);
  43508. });
  43509. }
  43510. else {
  43511. _this._createTexture();
  43512. }
  43513. _this._lastUpdate = BABYLON.Tools.Now;
  43514. return _this;
  43515. }
  43516. VideoTexture.prototype.__setTextureReady = function () {
  43517. this._texture.isReady = true;
  43518. };
  43519. VideoTexture.prototype._createTexture = function () {
  43520. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  43521. if (this._autoLaunch) {
  43522. this._autoLaunch = false;
  43523. this.video.play();
  43524. }
  43525. this._setTextureReady = this.__setTextureReady.bind(this);
  43526. this.video.addEventListener("playing", this._setTextureReady);
  43527. };
  43528. VideoTexture.prototype.update = function () {
  43529. var now = BABYLON.Tools.Now;
  43530. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  43531. return false;
  43532. }
  43533. this._lastUpdate = now;
  43534. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  43535. return true;
  43536. };
  43537. VideoTexture.prototype.dispose = function () {
  43538. _super.prototype.dispose.call(this);
  43539. this.video.removeEventListener("playing", this._setTextureReady);
  43540. };
  43541. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  43542. var video = document.createElement("video");
  43543. var constraintsDeviceId;
  43544. if (constraints && constraints.deviceId) {
  43545. constraintsDeviceId = {
  43546. exact: constraints.deviceId
  43547. };
  43548. }
  43549. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  43550. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  43551. if (navigator.getUserMedia) {
  43552. navigator.getUserMedia({
  43553. video: {
  43554. deviceId: constraintsDeviceId,
  43555. width: {
  43556. min: (constraints && constraints.minWidth) || 256,
  43557. max: (constraints && constraints.maxWidth) || 640
  43558. },
  43559. height: {
  43560. min: (constraints && constraints.minHeight) || 256,
  43561. max: (constraints && constraints.maxHeight) || 480
  43562. }
  43563. }
  43564. }, function (stream) {
  43565. if (video.mozSrcObject !== undefined) {
  43566. video.mozSrcObject = stream;
  43567. }
  43568. else {
  43569. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  43570. }
  43571. video.play();
  43572. if (onReady) {
  43573. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  43574. }
  43575. }, function (e) {
  43576. BABYLON.Tools.Error(e.name);
  43577. });
  43578. }
  43579. };
  43580. return VideoTexture;
  43581. }(BABYLON.Texture));
  43582. BABYLON.VideoTexture = VideoTexture;
  43583. })(BABYLON || (BABYLON = {}));
  43584. //# sourceMappingURL=babylon.videoTexture.js.map
  43585. var BABYLON;
  43586. (function (BABYLON) {
  43587. var RawTexture = (function (_super) {
  43588. __extends(RawTexture, _super);
  43589. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43591. if (invertY === void 0) { invertY = false; }
  43592. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43593. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  43594. _this.format = format;
  43595. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43596. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43597. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43598. return _this;
  43599. }
  43600. RawTexture.prototype.update = function (data) {
  43601. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43602. };
  43603. // Statics
  43604. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43605. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43606. if (invertY === void 0) { invertY = false; }
  43607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43608. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43609. };
  43610. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43612. if (invertY === void 0) { invertY = false; }
  43613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43614. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43615. };
  43616. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43617. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43618. if (invertY === void 0) { invertY = false; }
  43619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43620. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43621. };
  43622. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43624. if (invertY === void 0) { invertY = false; }
  43625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43626. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43627. };
  43628. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43629. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43630. if (invertY === void 0) { invertY = false; }
  43631. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43632. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43633. };
  43634. return RawTexture;
  43635. }(BABYLON.Texture));
  43636. BABYLON.RawTexture = RawTexture;
  43637. })(BABYLON || (BABYLON = {}));
  43638. //# sourceMappingURL=babylon.rawTexture.js.map
  43639. var BABYLON;
  43640. (function (BABYLON) {
  43641. var PostProcess = (function () {
  43642. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  43643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  43644. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43645. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  43646. if (blockCompilation === void 0) { blockCompilation = false; }
  43647. this.name = name;
  43648. this.width = -1;
  43649. this.height = -1;
  43650. this.autoClear = true;
  43651. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  43652. /*
  43653. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  43654. Can only be used on a single postprocess or on the last one of a chain.
  43655. */
  43656. this.enablePixelPerfectMode = false;
  43657. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  43658. this.alwaysForcePOT = false;
  43659. this.samples = 1;
  43660. this._reusable = false;
  43661. this._textures = new BABYLON.SmartArray(2);
  43662. this._currentRenderTextureInd = 0;
  43663. this._scaleRatio = new BABYLON.Vector2(1, 1);
  43664. this._texelSize = BABYLON.Vector2.Zero();
  43665. // Events
  43666. /**
  43667. * An event triggered when the postprocess is activated.
  43668. * @type {BABYLON.Observable}
  43669. */
  43670. this.onActivateObservable = new BABYLON.Observable();
  43671. /**
  43672. * An event triggered when the postprocess changes its size.
  43673. * @type {BABYLON.Observable}
  43674. */
  43675. this.onSizeChangedObservable = new BABYLON.Observable();
  43676. /**
  43677. * An event triggered when the postprocess applies its effect.
  43678. * @type {BABYLON.Observable}
  43679. */
  43680. this.onApplyObservable = new BABYLON.Observable();
  43681. /**
  43682. * An event triggered before rendering the postprocess
  43683. * @type {BABYLON.Observable}
  43684. */
  43685. this.onBeforeRenderObservable = new BABYLON.Observable();
  43686. /**
  43687. * An event triggered after rendering the postprocess
  43688. * @type {BABYLON.Observable}
  43689. */
  43690. this.onAfterRenderObservable = new BABYLON.Observable();
  43691. if (camera != null) {
  43692. this._camera = camera;
  43693. this._scene = camera.getScene();
  43694. camera.attachPostProcess(this);
  43695. this._engine = this._scene.getEngine();
  43696. }
  43697. else {
  43698. this._engine = engine;
  43699. }
  43700. this._options = options;
  43701. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  43702. this._reusable = reusable || false;
  43703. this._textureType = textureType;
  43704. this._samplers = samplers || [];
  43705. this._samplers.push("textureSampler");
  43706. this._fragmentUrl = fragmentUrl;
  43707. this._vertexUrl = vertexUrl;
  43708. this._parameters = parameters || [];
  43709. this._parameters.push("scale");
  43710. this._indexParameters = indexParameters;
  43711. if (!blockCompilation) {
  43712. this.updateEffect(defines);
  43713. }
  43714. }
  43715. Object.defineProperty(PostProcess.prototype, "onActivate", {
  43716. set: function (callback) {
  43717. if (this._onActivateObserver) {
  43718. this.onActivateObservable.remove(this._onActivateObserver);
  43719. }
  43720. this._onActivateObserver = this.onActivateObservable.add(callback);
  43721. },
  43722. enumerable: true,
  43723. configurable: true
  43724. });
  43725. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  43726. set: function (callback) {
  43727. if (this._onSizeChangedObserver) {
  43728. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  43729. }
  43730. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  43731. },
  43732. enumerable: true,
  43733. configurable: true
  43734. });
  43735. Object.defineProperty(PostProcess.prototype, "onApply", {
  43736. set: function (callback) {
  43737. if (this._onApplyObserver) {
  43738. this.onApplyObservable.remove(this._onApplyObserver);
  43739. }
  43740. this._onApplyObserver = this.onApplyObservable.add(callback);
  43741. },
  43742. enumerable: true,
  43743. configurable: true
  43744. });
  43745. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  43746. set: function (callback) {
  43747. if (this._onBeforeRenderObserver) {
  43748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  43749. }
  43750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  43751. },
  43752. enumerable: true,
  43753. configurable: true
  43754. });
  43755. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  43756. set: function (callback) {
  43757. if (this._onAfterRenderObserver) {
  43758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  43759. }
  43760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  43761. },
  43762. enumerable: true,
  43763. configurable: true
  43764. });
  43765. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  43766. get: function () {
  43767. return this._textures.data[this._currentRenderTextureInd];
  43768. },
  43769. set: function (value) {
  43770. this._forcedOutputTexture = value;
  43771. },
  43772. enumerable: true,
  43773. configurable: true
  43774. });
  43775. PostProcess.prototype.getCamera = function () {
  43776. return this._camera;
  43777. };
  43778. Object.defineProperty(PostProcess.prototype, "texelSize", {
  43779. get: function () {
  43780. if (this._shareOutputWithPostProcess) {
  43781. return this._shareOutputWithPostProcess.texelSize;
  43782. }
  43783. if (this._forcedOutputTexture) {
  43784. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  43785. }
  43786. return this._texelSize;
  43787. },
  43788. enumerable: true,
  43789. configurable: true
  43790. });
  43791. PostProcess.prototype.getEngine = function () {
  43792. return this._engine;
  43793. };
  43794. PostProcess.prototype.shareOutputWith = function (postProcess) {
  43795. this._disposeTextures();
  43796. this._shareOutputWithPostProcess = postProcess;
  43797. return this;
  43798. };
  43799. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  43800. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  43801. };
  43802. PostProcess.prototype.isReusable = function () {
  43803. return this._reusable;
  43804. };
  43805. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  43806. PostProcess.prototype.markTextureDirty = function () {
  43807. this.width = -1;
  43808. };
  43809. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  43810. var _this = this;
  43811. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  43812. camera = camera || this._camera;
  43813. var scene = camera.getScene();
  43814. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  43815. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  43816. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  43817. var desiredWidth = this._options.width || requiredWidth;
  43818. var desiredHeight = this._options.height || requiredHeight;
  43819. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  43820. if (!this._options.width) {
  43821. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  43822. }
  43823. if (!this._options.height) {
  43824. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  43825. }
  43826. }
  43827. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  43828. if (this._textures.length > 0) {
  43829. for (var i = 0; i < this._textures.length; i++) {
  43830. this._engine._releaseTexture(this._textures.data[i]);
  43831. }
  43832. this._textures.reset();
  43833. }
  43834. this.width = desiredWidth;
  43835. this.height = desiredHeight;
  43836. var textureSize = { width: this.width, height: this.height };
  43837. var textureOptions = {
  43838. generateMipMaps: false,
  43839. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  43840. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  43841. samplingMode: this.renderTargetSamplingMode,
  43842. type: this._textureType
  43843. };
  43844. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43845. if (this._reusable) {
  43846. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  43847. }
  43848. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  43849. this.onSizeChangedObservable.notifyObservers(this);
  43850. }
  43851. this._textures.forEach(function (texture) {
  43852. if (texture.samples !== _this.samples) {
  43853. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  43854. }
  43855. });
  43856. }
  43857. var target;
  43858. if (this._shareOutputWithPostProcess) {
  43859. target = this._shareOutputWithPostProcess.outputTexture;
  43860. }
  43861. else if (this._forcedOutputTexture) {
  43862. target = this._forcedOutputTexture;
  43863. this.width = this._forcedOutputTexture._width;
  43864. this.height = this._forcedOutputTexture._height;
  43865. }
  43866. else {
  43867. target = this.outputTexture;
  43868. }
  43869. if (this.enablePixelPerfectMode) {
  43870. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  43871. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  43872. }
  43873. else {
  43874. this._scaleRatio.copyFromFloats(1, 1);
  43875. this._engine.bindFramebuffer(target);
  43876. }
  43877. this.onActivateObservable.notifyObservers(camera);
  43878. // Clear
  43879. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  43880. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  43881. }
  43882. if (this._reusable) {
  43883. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  43884. }
  43885. };
  43886. Object.defineProperty(PostProcess.prototype, "isSupported", {
  43887. get: function () {
  43888. return this._effect.isSupported;
  43889. },
  43890. enumerable: true,
  43891. configurable: true
  43892. });
  43893. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  43894. get: function () {
  43895. if (this._shareOutputWithPostProcess) {
  43896. return this._shareOutputWithPostProcess.aspectRatio;
  43897. }
  43898. if (this._forcedOutputTexture) {
  43899. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  43900. }
  43901. return this.width / this.height;
  43902. },
  43903. enumerable: true,
  43904. configurable: true
  43905. });
  43906. PostProcess.prototype.apply = function () {
  43907. // Check
  43908. if (!this._effect || !this._effect.isReady())
  43909. return null;
  43910. // States
  43911. this._engine.enableEffect(this._effect);
  43912. this._engine.setState(false);
  43913. this._engine.setDepthBuffer(false);
  43914. this._engine.setDepthWrite(false);
  43915. // Alpha
  43916. this._engine.setAlphaMode(this.alphaMode);
  43917. if (this.alphaConstants) {
  43918. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  43919. }
  43920. // Texture
  43921. var source;
  43922. if (this._shareOutputWithPostProcess) {
  43923. source = this._shareOutputWithPostProcess.outputTexture;
  43924. }
  43925. else if (this._forcedOutputTexture) {
  43926. source = this._forcedOutputTexture;
  43927. }
  43928. else {
  43929. source = this.outputTexture;
  43930. }
  43931. this._effect._bindTexture("textureSampler", source);
  43932. // Parameters
  43933. this._effect.setVector2("scale", this._scaleRatio);
  43934. this.onApplyObservable.notifyObservers(this._effect);
  43935. return this._effect;
  43936. };
  43937. PostProcess.prototype._disposeTextures = function () {
  43938. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  43939. return;
  43940. }
  43941. if (this._textures.length > 0) {
  43942. for (var i = 0; i < this._textures.length; i++) {
  43943. this._engine._releaseTexture(this._textures.data[i]);
  43944. }
  43945. }
  43946. this._textures.dispose();
  43947. };
  43948. PostProcess.prototype.dispose = function (camera) {
  43949. camera = camera || this._camera;
  43950. this._disposeTextures();
  43951. if (!camera) {
  43952. return;
  43953. }
  43954. camera.detachPostProcess(this);
  43955. var index = camera._postProcesses.indexOf(this);
  43956. if (index === 0 && camera._postProcesses.length > 0) {
  43957. this._camera._postProcesses[0].markTextureDirty();
  43958. }
  43959. this.onActivateObservable.clear();
  43960. this.onAfterRenderObservable.clear();
  43961. this.onApplyObservable.clear();
  43962. this.onBeforeRenderObservable.clear();
  43963. this.onSizeChangedObservable.clear();
  43964. };
  43965. return PostProcess;
  43966. }());
  43967. BABYLON.PostProcess = PostProcess;
  43968. })(BABYLON || (BABYLON = {}));
  43969. //# sourceMappingURL=babylon.postProcess.js.map
  43970. var BABYLON;
  43971. (function (BABYLON) {
  43972. var PassPostProcess = (function (_super) {
  43973. __extends(PassPostProcess, _super);
  43974. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  43975. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  43976. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  43977. }
  43978. return PassPostProcess;
  43979. }(BABYLON.PostProcess));
  43980. BABYLON.PassPostProcess = PassPostProcess;
  43981. })(BABYLON || (BABYLON = {}));
  43982. //# sourceMappingURL=babylon.passPostProcess.js.map
  43983. var BABYLON;
  43984. (function (BABYLON) {
  43985. var ShadowGenerator = (function () {
  43986. /**
  43987. * Creates a ShadowGenerator object.
  43988. * A ShadowGenerator is the required tool to use the shadows.
  43989. * Each light casting shadows needs to use its own ShadowGenerator.
  43990. * Required parameters :
  43991. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  43992. * - `light` : the light object generating the shadows.
  43993. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  43994. */
  43995. function ShadowGenerator(mapSize, light) {
  43996. // Members
  43997. this._filter = ShadowGenerator.FILTER_NONE;
  43998. this.blurScale = 2;
  43999. this._blurBoxOffset = 0;
  44000. this._bias = 0.00005;
  44001. this._lightDirection = BABYLON.Vector3.Zero();
  44002. this.forceBackFacesOnly = false;
  44003. this._darkness = 0;
  44004. this._transparencyShadow = false;
  44005. this._viewMatrix = BABYLON.Matrix.Zero();
  44006. this._projectionMatrix = BABYLON.Matrix.Zero();
  44007. this._transformMatrix = BABYLON.Matrix.Zero();
  44008. this._worldViewProjection = BABYLON.Matrix.Zero();
  44009. this._currentFaceIndex = 0;
  44010. this._currentFaceIndexCache = 0;
  44011. this._isCube = false;
  44012. this._mapSize = mapSize;
  44013. this._light = light;
  44014. this._scene = light.getScene();
  44015. light._shadowGenerator = this;
  44016. // Texture type fallback from float to int if not supported.
  44017. var caps = this._scene.getEngine().getCaps();
  44018. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  44019. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44020. }
  44021. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  44022. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  44023. }
  44024. else {
  44025. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44026. }
  44027. this._initializeGenerator(1);
  44028. }
  44029. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  44030. // Static
  44031. get: function () {
  44032. return ShadowGenerator._FILTER_NONE;
  44033. },
  44034. enumerable: true,
  44035. configurable: true
  44036. });
  44037. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  44038. get: function () {
  44039. return ShadowGenerator._FILTER_POISSONSAMPLING;
  44040. },
  44041. enumerable: true,
  44042. configurable: true
  44043. });
  44044. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  44045. get: function () {
  44046. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  44047. },
  44048. enumerable: true,
  44049. configurable: true
  44050. });
  44051. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  44052. get: function () {
  44053. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  44054. },
  44055. enumerable: true,
  44056. configurable: true
  44057. });
  44058. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  44059. get: function () {
  44060. return this._bias;
  44061. },
  44062. set: function (bias) {
  44063. this._bias = bias;
  44064. },
  44065. enumerable: true,
  44066. configurable: true
  44067. });
  44068. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  44069. get: function () {
  44070. return this._blurBoxOffset;
  44071. },
  44072. set: function (value) {
  44073. var _this = this;
  44074. if (this._blurBoxOffset === value) {
  44075. return;
  44076. }
  44077. this._blurBoxOffset = value;
  44078. if (this._boxBlurPostprocess) {
  44079. this._boxBlurPostprocess.dispose();
  44080. }
  44081. 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, this._textureType);
  44082. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  44083. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  44084. });
  44085. },
  44086. enumerable: true,
  44087. configurable: true
  44088. });
  44089. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  44090. get: function () {
  44091. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  44092. },
  44093. set: function (value) {
  44094. this._depthScale = value;
  44095. },
  44096. enumerable: true,
  44097. configurable: true
  44098. });
  44099. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  44100. get: function () {
  44101. return this._filter;
  44102. },
  44103. set: function (value) {
  44104. if (this._filter === value) {
  44105. return;
  44106. }
  44107. this._filter = value;
  44108. this._applyFilterValues();
  44109. this._light._markMeshesAsLightDirty();
  44110. },
  44111. enumerable: true,
  44112. configurable: true
  44113. });
  44114. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  44115. get: function () {
  44116. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44117. return this.useExponentialShadowMap;
  44118. },
  44119. set: function (value) {
  44120. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  44121. this.useExponentialShadowMap = value;
  44122. },
  44123. enumerable: true,
  44124. configurable: true
  44125. });
  44126. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  44127. get: function () {
  44128. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  44129. },
  44130. set: function (value) {
  44131. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  44137. get: function () {
  44138. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  44139. },
  44140. set: function (value) {
  44141. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  44142. },
  44143. enumerable: true,
  44144. configurable: true
  44145. });
  44146. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  44147. get: function () {
  44148. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44149. return this.useBlurExponentialShadowMap;
  44150. },
  44151. set: function (value) {
  44152. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  44153. this.useBlurExponentialShadowMap = value;
  44154. },
  44155. enumerable: true,
  44156. configurable: true
  44157. });
  44158. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  44159. get: function () {
  44160. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  44161. },
  44162. set: function (value) {
  44163. if (this._light.needCube() && value) {
  44164. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  44165. }
  44166. else {
  44167. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  44168. }
  44169. },
  44170. enumerable: true,
  44171. configurable: true
  44172. });
  44173. ShadowGenerator.prototype._initializeGenerator = function (boxBlurOffset) {
  44174. var _this = this;
  44175. var light = this._light;
  44176. var scene = this._scene;
  44177. var textureType = this._textureType;
  44178. light._markMeshesAsLightDirty();
  44179. // Render target
  44180. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", this._mapSize, this._scene, false, true, textureType, light.needCube());
  44181. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44182. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44183. this._shadowMap.anisotropicFilteringLevel = 1;
  44184. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44185. this._shadowMap.renderParticles = false;
  44186. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  44187. _this._currentFaceIndex = faceIndex;
  44188. });
  44189. this._shadowMap.onAfterUnbindObservable.add(function () {
  44190. if (!_this.useBlurExponentialShadowMap) {
  44191. return;
  44192. }
  44193. if (!_this._shadowMap2) {
  44194. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", _this._mapSize, _this._scene, false, true, textureType);
  44195. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44196. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44197. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44198. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  44199. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  44200. effect.setTexture("textureSampler", _this._shadowMap);
  44201. });
  44202. _this.blurBoxOffset = boxBlurOffset;
  44203. }
  44204. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  44205. });
  44206. // Custom render function
  44207. var renderSubMesh = function (subMesh) {
  44208. var mesh = subMesh.getRenderingMesh();
  44209. var scene = _this._scene;
  44210. var engine = scene.getEngine();
  44211. // Culling
  44212. engine.setState(subMesh.getMaterial().backFaceCulling);
  44213. // Managing instances
  44214. var batch = mesh._getInstancesRenderList(subMesh._id);
  44215. if (batch.mustReturn) {
  44216. return;
  44217. }
  44218. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44219. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  44220. engine.enableEffect(_this._effect);
  44221. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  44222. var material = subMesh.getMaterial();
  44223. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  44224. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  44225. _this._effect.setVector3("lightPosition", _this.getLight().position);
  44226. if (_this.getLight().needCube()) {
  44227. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  44228. }
  44229. // Alpha test
  44230. if (material && material.needAlphaTesting()) {
  44231. var alphaTexture = material.getAlphaTestTexture();
  44232. _this._effect.setTexture("diffuseSampler", alphaTexture);
  44233. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44234. }
  44235. // Bones
  44236. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44237. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44238. }
  44239. if (_this.forceBackFacesOnly) {
  44240. engine.setState(true, 0, false, true);
  44241. }
  44242. // Draw
  44243. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  44244. if (_this.forceBackFacesOnly) {
  44245. engine.setState(true, 0, false, false);
  44246. }
  44247. }
  44248. else {
  44249. // Need to reset refresh rate of the shadowMap
  44250. _this._shadowMap.resetRefreshCounter();
  44251. }
  44252. };
  44253. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  44254. var index;
  44255. for (index = 0; index < opaqueSubMeshes.length; index++) {
  44256. renderSubMesh(opaqueSubMeshes.data[index]);
  44257. }
  44258. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  44259. renderSubMesh(alphaTestSubMeshes.data[index]);
  44260. }
  44261. if (_this._transparencyShadow) {
  44262. for (index = 0; index < transparentSubMeshes.length; index++) {
  44263. renderSubMesh(transparentSubMeshes.data[index]);
  44264. }
  44265. }
  44266. };
  44267. this._shadowMap.onClearObservable.add(function (engine) {
  44268. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  44269. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  44270. }
  44271. else {
  44272. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  44273. }
  44274. });
  44275. };
  44276. ShadowGenerator.prototype._applyFilterValues = function () {
  44277. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44278. this._shadowMap.anisotropicFilteringLevel = 16;
  44279. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  44280. }
  44281. else {
  44282. this._shadowMap.anisotropicFilteringLevel = 1;
  44283. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  44284. }
  44285. };
  44286. ShadowGenerator.prototype.recreateShadowMap = function () {
  44287. // Track render list.
  44288. var renderList = this._shadowMap.renderList;
  44289. // Clean up existing data.
  44290. this._disposeRTTandPostProcesses();
  44291. // Reinitializes.
  44292. this._initializeGenerator(this.blurBoxOffset);
  44293. // Reaffect the blur ESM to ensure a correct fallback if necessary.
  44294. if (this.useBlurExponentialShadowMap) {
  44295. this.useBlurExponentialShadowMap = true;
  44296. }
  44297. // Reaffect the filter.
  44298. this._applyFilterValues();
  44299. // Reaffect Render List.
  44300. this._shadowMap.renderList = renderList;
  44301. };
  44302. /**
  44303. * Boolean : true when the ShadowGenerator is finally computed.
  44304. */
  44305. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  44306. var defines = [];
  44307. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44308. defines.push("#define FLOAT");
  44309. }
  44310. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44311. defines.push("#define ESM");
  44312. }
  44313. if (this.getLight().needCube()) {
  44314. defines.push("#define CUBEMAP");
  44315. }
  44316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44317. var mesh = subMesh.getMesh();
  44318. var material = subMesh.getMaterial();
  44319. // Alpha test
  44320. if (material && material.needAlphaTesting()) {
  44321. defines.push("#define ALPHATEST");
  44322. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44323. attribs.push(BABYLON.VertexBuffer.UVKind);
  44324. defines.push("#define UV1");
  44325. }
  44326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44327. var alphaTexture = material.getAlphaTestTexture();
  44328. if (alphaTexture.coordinatesIndex === 1) {
  44329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44330. defines.push("#define UV2");
  44331. }
  44332. }
  44333. }
  44334. // Bones
  44335. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44336. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44337. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44338. if (mesh.numBoneInfluencers > 4) {
  44339. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44340. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44341. }
  44342. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44343. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44344. }
  44345. else {
  44346. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44347. }
  44348. // Instances
  44349. if (useInstances) {
  44350. defines.push("#define INSTANCES");
  44351. attribs.push("world0");
  44352. attribs.push("world1");
  44353. attribs.push("world2");
  44354. attribs.push("world3");
  44355. }
  44356. // Get correct effect
  44357. var join = defines.join("\n");
  44358. if (this._cachedDefines !== join) {
  44359. this._cachedDefines = join;
  44360. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  44361. }
  44362. return this._effect.isReady();
  44363. };
  44364. /**
  44365. * Returns a RenderTargetTexture object : the shadow map texture.
  44366. */
  44367. ShadowGenerator.prototype.getShadowMap = function () {
  44368. return this._shadowMap;
  44369. };
  44370. /**
  44371. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  44372. */
  44373. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  44374. if (this._shadowMap2) {
  44375. return this._shadowMap2;
  44376. }
  44377. return this._shadowMap;
  44378. };
  44379. /**
  44380. * Returns the associated light object.
  44381. */
  44382. ShadowGenerator.prototype.getLight = function () {
  44383. return this._light;
  44384. };
  44385. // Methods
  44386. /**
  44387. * Returns a Matrix object : the updated transformation matrix.
  44388. */
  44389. ShadowGenerator.prototype.getTransformMatrix = function () {
  44390. var scene = this._scene;
  44391. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  44392. return this._transformMatrix;
  44393. }
  44394. this._currentRenderID = scene.getRenderId();
  44395. this._currentFaceIndexCache = this._currentFaceIndex;
  44396. var lightPosition = this._light.position;
  44397. if (this._light.computeTransformedInformation()) {
  44398. lightPosition = this._light.transformedPosition;
  44399. }
  44400. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  44401. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  44402. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  44403. }
  44404. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  44405. this._cachedPosition = lightPosition.clone();
  44406. this._cachedDirection = this._lightDirection.clone();
  44407. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  44408. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  44409. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  44410. }
  44411. return this._transformMatrix;
  44412. };
  44413. /**
  44414. * Returns the darkness value (float).
  44415. */
  44416. ShadowGenerator.prototype.getDarkness = function () {
  44417. return this._darkness;
  44418. };
  44419. /**
  44420. * Sets the ShadowGenerator darkness value (float <= 1.0).
  44421. * Returns the ShadowGenerator.
  44422. */
  44423. ShadowGenerator.prototype.setDarkness = function (darkness) {
  44424. if (darkness >= 1.0)
  44425. this._darkness = 1.0;
  44426. else if (darkness <= 0.0)
  44427. this._darkness = 0.0;
  44428. else
  44429. this._darkness = darkness;
  44430. return this;
  44431. };
  44432. /**
  44433. * Sets the ability to have transparent shadow (boolean).
  44434. * Returns the ShadowGenerator.
  44435. */
  44436. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  44437. this._transparencyShadow = hasShadow;
  44438. return this;
  44439. };
  44440. ShadowGenerator.prototype._packHalf = function (depth) {
  44441. var scale = depth * 255.0;
  44442. var fract = scale - Math.floor(scale);
  44443. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  44444. };
  44445. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  44446. if (this._shadowMap) {
  44447. this._shadowMap.dispose();
  44448. this._shadowMap = null;
  44449. }
  44450. if (this._shadowMap2) {
  44451. this._shadowMap2.dispose();
  44452. this._shadowMap2 = null;
  44453. }
  44454. if (this._downSamplePostprocess) {
  44455. this._downSamplePostprocess.dispose();
  44456. this._downSamplePostprocess = null;
  44457. }
  44458. if (this._boxBlurPostprocess) {
  44459. this._boxBlurPostprocess.dispose();
  44460. this._boxBlurPostprocess = null;
  44461. }
  44462. };
  44463. /**
  44464. * Disposes the ShadowGenerator.
  44465. * Returns nothing.
  44466. */
  44467. ShadowGenerator.prototype.dispose = function () {
  44468. this._disposeRTTandPostProcesses();
  44469. this._light._shadowGenerator = null;
  44470. this._light._markMeshesAsLightDirty();
  44471. };
  44472. /**
  44473. * Serializes the ShadowGenerator and returns a serializationObject.
  44474. */
  44475. ShadowGenerator.prototype.serialize = function () {
  44476. var serializationObject = {};
  44477. var shadowMap = this.getShadowMap();
  44478. serializationObject.lightId = this._light.id;
  44479. serializationObject.mapSize = shadowMap.getRenderSize();
  44480. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  44481. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  44482. serializationObject.usePoissonSampling = this.usePoissonSampling;
  44483. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  44484. serializationObject.depthScale = this.depthScale;
  44485. serializationObject.darkness = this.getDarkness();
  44486. serializationObject.renderList = [];
  44487. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  44488. var mesh = shadowMap.renderList[meshIndex];
  44489. serializationObject.renderList.push(mesh.id);
  44490. }
  44491. return serializationObject;
  44492. };
  44493. /**
  44494. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  44495. */
  44496. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  44497. //casting to point light, as light is missing the position attr and typescript complains.
  44498. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  44499. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  44500. var shadowMap = shadowGenerator.getShadowMap();
  44501. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  44502. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  44503. meshes.forEach(function (mesh) {
  44504. shadowMap.renderList.push(mesh);
  44505. });
  44506. }
  44507. if (parsedShadowGenerator.usePoissonSampling) {
  44508. shadowGenerator.usePoissonSampling = true;
  44509. }
  44510. else if (parsedShadowGenerator.useExponentialShadowMap) {
  44511. shadowGenerator.useExponentialShadowMap = true;
  44512. }
  44513. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  44514. shadowGenerator.useBlurExponentialShadowMap = true;
  44515. }
  44516. else if (parsedShadowGenerator.useVarianceShadowMap) {
  44517. shadowGenerator.useExponentialShadowMap = true;
  44518. }
  44519. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  44520. shadowGenerator.useBlurExponentialShadowMap = true;
  44521. }
  44522. if (parsedShadowGenerator.depthScale) {
  44523. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  44524. }
  44525. if (parsedShadowGenerator.blurScale) {
  44526. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  44527. }
  44528. if (parsedShadowGenerator.blurBoxOffset) {
  44529. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  44530. }
  44531. if (parsedShadowGenerator.bias !== undefined) {
  44532. shadowGenerator.bias = parsedShadowGenerator.bias;
  44533. }
  44534. if (parsedShadowGenerator.darkness) {
  44535. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  44536. }
  44537. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  44538. return shadowGenerator;
  44539. };
  44540. /**
  44541. * This creates the defines related to the standard BJS materials.
  44542. */
  44543. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  44544. var scene = this._scene;
  44545. var light = this._light;
  44546. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44547. return;
  44548. }
  44549. defines["SHADOW" + lightIndex] = true;
  44550. if (this.usePoissonSampling) {
  44551. defines["SHADOWPCF" + lightIndex] = true;
  44552. }
  44553. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  44554. defines["SHADOWESM" + lightIndex] = true;
  44555. }
  44556. if (light.needCube()) {
  44557. defines["SHADOWCUBE" + lightIndex] = true;
  44558. }
  44559. };
  44560. /**
  44561. * This binds shadow lights related to the standard BJS materials.
  44562. * It implies the unifroms available on the materials are the standard BJS ones.
  44563. */
  44564. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect, depthValuesAlreadySet) {
  44565. var light = this._light;
  44566. var scene = this._scene;
  44567. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  44568. return;
  44569. }
  44570. if (!light.needCube()) {
  44571. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  44572. }
  44573. else {
  44574. if (!depthValuesAlreadySet) {
  44575. depthValuesAlreadySet = true;
  44576. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  44577. }
  44578. }
  44579. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  44580. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  44581. return depthValuesAlreadySet;
  44582. };
  44583. return ShadowGenerator;
  44584. }());
  44585. ShadowGenerator._FILTER_NONE = 0;
  44586. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  44587. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  44588. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  44589. BABYLON.ShadowGenerator = ShadowGenerator;
  44590. })(BABYLON || (BABYLON = {}));
  44591. //# sourceMappingURL=babylon.shadowGenerator.js.map
  44592. var BABYLON;
  44593. (function (BABYLON) {
  44594. var DefaultLoadingScreen = (function () {
  44595. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  44596. if (_loadingText === void 0) { _loadingText = ""; }
  44597. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  44598. var _this = this;
  44599. this._renderingCanvas = _renderingCanvas;
  44600. this._loadingText = _loadingText;
  44601. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  44602. // Resize
  44603. this._resizeLoadingUI = function () {
  44604. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  44605. _this._loadingDiv.style.position = "absolute";
  44606. _this._loadingDiv.style.left = canvasRect.left + "px";
  44607. _this._loadingDiv.style.top = canvasRect.top + "px";
  44608. _this._loadingDiv.style.width = canvasRect.width + "px";
  44609. _this._loadingDiv.style.height = canvasRect.height + "px";
  44610. };
  44611. }
  44612. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  44613. var _this = this;
  44614. if (this._loadingDiv) {
  44615. // Do not add a loading screen if there is already one
  44616. return;
  44617. }
  44618. this._loadingDiv = document.createElement("div");
  44619. this._loadingDiv.id = "babylonjsLoadingDiv";
  44620. this._loadingDiv.style.opacity = "0";
  44621. this._loadingDiv.style.transition = "opacity 1.5s ease";
  44622. // Loading text
  44623. this._loadingTextDiv = document.createElement("div");
  44624. this._loadingTextDiv.style.position = "absolute";
  44625. this._loadingTextDiv.style.left = "0";
  44626. this._loadingTextDiv.style.top = "50%";
  44627. this._loadingTextDiv.style.marginTop = "80px";
  44628. this._loadingTextDiv.style.width = "100%";
  44629. this._loadingTextDiv.style.height = "20px";
  44630. this._loadingTextDiv.style.fontFamily = "Arial";
  44631. this._loadingTextDiv.style.fontSize = "14px";
  44632. this._loadingTextDiv.style.color = "white";
  44633. this._loadingTextDiv.style.textAlign = "center";
  44634. this._loadingTextDiv.innerHTML = "Loading";
  44635. this._loadingDiv.appendChild(this._loadingTextDiv);
  44636. //set the predefined text
  44637. this._loadingTextDiv.innerHTML = this._loadingText;
  44638. // Loading img
  44639. var imgBack = new Image();
  44640. 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==";
  44641. imgBack.style.position = "absolute";
  44642. imgBack.style.left = "50%";
  44643. imgBack.style.top = "50%";
  44644. imgBack.style.marginLeft = "-50px";
  44645. imgBack.style.marginTop = "-50px";
  44646. imgBack.style.transition = "transform 1.0s ease";
  44647. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  44648. var deg = 360;
  44649. var onTransitionEnd = function () {
  44650. deg += 360;
  44651. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  44652. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  44653. };
  44654. imgBack.addEventListener("transitionend", onTransitionEnd);
  44655. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  44656. this._loadingDiv.appendChild(imgBack);
  44657. // front image
  44658. var imgFront = new Image();
  44659. 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=";
  44660. imgFront.style.position = "absolute";
  44661. imgFront.style.left = "50%";
  44662. imgFront.style.top = "50%";
  44663. imgFront.style.marginLeft = "-50px";
  44664. imgFront.style.marginTop = "-50px";
  44665. this._loadingDiv.appendChild(imgFront);
  44666. this._resizeLoadingUI();
  44667. window.addEventListener("resize", this._resizeLoadingUI);
  44668. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44669. document.body.appendChild(this._loadingDiv);
  44670. setTimeout(function () {
  44671. _this._loadingDiv.style.opacity = "1";
  44672. imgBack.style.transform = "rotateZ(360deg)";
  44673. imgBack.style.webkitTransform = "rotateZ(360deg)";
  44674. }, 0);
  44675. };
  44676. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  44677. var _this = this;
  44678. if (!this._loadingDiv) {
  44679. return;
  44680. }
  44681. var onTransitionEnd = function () {
  44682. if (!_this._loadingDiv) {
  44683. return;
  44684. }
  44685. document.body.removeChild(_this._loadingDiv);
  44686. window.removeEventListener("resize", _this._resizeLoadingUI);
  44687. _this._loadingDiv = null;
  44688. };
  44689. this._loadingDiv.style.opacity = "0";
  44690. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  44691. };
  44692. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  44693. set: function (text) {
  44694. this._loadingText = text;
  44695. if (this._loadingTextDiv) {
  44696. this._loadingTextDiv.innerHTML = this._loadingText;
  44697. }
  44698. },
  44699. enumerable: true,
  44700. configurable: true
  44701. });
  44702. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  44703. get: function () {
  44704. return this._loadingDivBackgroundColor;
  44705. },
  44706. set: function (color) {
  44707. this._loadingDivBackgroundColor = color;
  44708. if (!this._loadingDiv) {
  44709. return;
  44710. }
  44711. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  44712. },
  44713. enumerable: true,
  44714. configurable: true
  44715. });
  44716. return DefaultLoadingScreen;
  44717. }());
  44718. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  44719. })(BABYLON || (BABYLON = {}));
  44720. //# sourceMappingURL=babylon.loadingScreen.js.map
  44721. var BABYLON;
  44722. (function (BABYLON) {
  44723. var SceneLoader = (function () {
  44724. function SceneLoader() {
  44725. }
  44726. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  44727. get: function () {
  44728. return 0;
  44729. },
  44730. enumerable: true,
  44731. configurable: true
  44732. });
  44733. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  44734. get: function () {
  44735. return 1;
  44736. },
  44737. enumerable: true,
  44738. configurable: true
  44739. });
  44740. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  44741. get: function () {
  44742. return 2;
  44743. },
  44744. enumerable: true,
  44745. configurable: true
  44746. });
  44747. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  44748. get: function () {
  44749. return 3;
  44750. },
  44751. enumerable: true,
  44752. configurable: true
  44753. });
  44754. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  44755. get: function () {
  44756. return SceneLoader._ForceFullSceneLoadingForIncremental;
  44757. },
  44758. set: function (value) {
  44759. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  44760. },
  44761. enumerable: true,
  44762. configurable: true
  44763. });
  44764. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  44765. get: function () {
  44766. return SceneLoader._ShowLoadingScreen;
  44767. },
  44768. set: function (value) {
  44769. SceneLoader._ShowLoadingScreen = value;
  44770. },
  44771. enumerable: true,
  44772. configurable: true
  44773. });
  44774. Object.defineProperty(SceneLoader, "loggingLevel", {
  44775. get: function () {
  44776. return SceneLoader._loggingLevel;
  44777. },
  44778. set: function (value) {
  44779. SceneLoader._loggingLevel = value;
  44780. },
  44781. enumerable: true,
  44782. configurable: true
  44783. });
  44784. SceneLoader._getDefaultPlugin = function () {
  44785. return SceneLoader._registeredPlugins[".babylon"];
  44786. };
  44787. SceneLoader._getPluginForExtension = function (extension) {
  44788. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  44789. if (registeredPlugin) {
  44790. return registeredPlugin;
  44791. }
  44792. return SceneLoader._getDefaultPlugin();
  44793. };
  44794. SceneLoader._getPluginForDirectLoad = function (data) {
  44795. for (var extension in SceneLoader._registeredPlugins) {
  44796. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  44797. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  44798. return SceneLoader._registeredPlugins[extension];
  44799. }
  44800. }
  44801. return SceneLoader._getDefaultPlugin();
  44802. };
  44803. SceneLoader._getPluginForFilename = function (sceneFilename) {
  44804. if (sceneFilename.name) {
  44805. sceneFilename = sceneFilename.name;
  44806. }
  44807. var dotPosition = sceneFilename.lastIndexOf(".");
  44808. var queryStringPosition = sceneFilename.indexOf("?");
  44809. if (queryStringPosition === -1) {
  44810. queryStringPosition = sceneFilename.length;
  44811. }
  44812. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  44813. return SceneLoader._getPluginForExtension(extension);
  44814. };
  44815. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  44816. SceneLoader._getDirectLoad = function (sceneFilename) {
  44817. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  44818. return sceneFilename.substr(5);
  44819. }
  44820. return null;
  44821. };
  44822. // Public functions
  44823. SceneLoader.GetPluginForExtension = function (extension) {
  44824. return SceneLoader._getPluginForExtension(extension).plugin;
  44825. };
  44826. SceneLoader.RegisterPlugin = function (plugin) {
  44827. if (typeof plugin.extensions === "string") {
  44828. var extension = plugin.extensions;
  44829. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44830. plugin: plugin,
  44831. isBinary: false
  44832. };
  44833. }
  44834. else {
  44835. var extensions = plugin.extensions;
  44836. Object.keys(extensions).forEach(function (extension) {
  44837. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  44838. plugin: plugin,
  44839. isBinary: extensions[extension].isBinary
  44840. };
  44841. });
  44842. }
  44843. };
  44844. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44845. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44846. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44847. return;
  44848. }
  44849. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44850. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44851. return;
  44852. }
  44853. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44854. var loadingToken = {};
  44855. scene._addPendingData(loadingToken);
  44856. var manifestChecked = function (success) {
  44857. scene.database = database;
  44858. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  44859. var plugin = registeredPlugin.plugin;
  44860. var useArrayBuffer = registeredPlugin.isBinary;
  44861. var importMeshFromData = function (data) {
  44862. var meshes = [];
  44863. var particleSystems = [];
  44864. var skeletons = [];
  44865. if (scene.isDisposed) {
  44866. if (onerror) {
  44867. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  44868. }
  44869. return;
  44870. }
  44871. try {
  44872. if (plugin.importMesh) {
  44873. var syncedPlugin = plugin;
  44874. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  44875. if (onerror) {
  44876. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44877. }
  44878. scene._removePendingData(loadingToken);
  44879. return;
  44880. }
  44881. if (onsuccess) {
  44882. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44883. onsuccess(meshes, particleSystems, skeletons);
  44884. scene._removePendingData(loadingToken);
  44885. }
  44886. }
  44887. else {
  44888. var asyncedPlugin = plugin;
  44889. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  44890. if (onsuccess) {
  44891. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  44892. onsuccess(meshes, particleSystems, skeletons);
  44893. scene._removePendingData(loadingToken);
  44894. }
  44895. }, function () {
  44896. if (onerror) {
  44897. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  44898. }
  44899. scene._removePendingData(loadingToken);
  44900. });
  44901. }
  44902. }
  44903. catch (e) {
  44904. if (onerror) {
  44905. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  44906. }
  44907. scene._removePendingData(loadingToken);
  44908. }
  44909. };
  44910. if (directLoad) {
  44911. importMeshFromData(directLoad);
  44912. return;
  44913. }
  44914. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  44915. importMeshFromData(data);
  44916. }, progressCallBack, database, useArrayBuffer, function () {
  44917. if (onerror) {
  44918. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  44919. }
  44920. });
  44921. };
  44922. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  44923. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  44924. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  44925. }
  44926. else {
  44927. // If the scene is a data stream or offline support is not enabled, it's a direct load
  44928. manifestChecked(true);
  44929. }
  44930. };
  44931. /**
  44932. * Load a scene
  44933. * @param rootUrl a string that defines the root url for scene and resources
  44934. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44935. * @param engine is the instance of BABYLON.Engine to use to create the scene
  44936. */
  44937. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  44938. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  44939. };
  44940. /**
  44941. * Append a scene
  44942. * @param rootUrl a string that defines the root url for scene and resources
  44943. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  44944. * @param scene is the instance of BABYLON.Scene to append to
  44945. */
  44946. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  44947. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  44948. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  44949. return;
  44950. }
  44951. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  44952. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  44953. var plugin = registeredPlugin.plugin;
  44954. var useArrayBuffer = registeredPlugin.isBinary;
  44955. var database;
  44956. var loadingToken = {};
  44957. scene._addPendingData(loadingToken);
  44958. if (SceneLoader.ShowLoadingScreen) {
  44959. scene.getEngine().displayLoadingUI();
  44960. }
  44961. var loadSceneFromData = function (data) {
  44962. scene.database = database;
  44963. if (plugin.load) {
  44964. var syncedPlugin = plugin;
  44965. if (!syncedPlugin.load(scene, data, rootUrl)) {
  44966. if (onerror) {
  44967. onerror(scene);
  44968. }
  44969. scene._removePendingData(loadingToken);
  44970. scene.getEngine().hideLoadingUI();
  44971. return;
  44972. }
  44973. if (onsuccess) {
  44974. onsuccess(scene);
  44975. }
  44976. scene._removePendingData(loadingToken);
  44977. }
  44978. else {
  44979. var asyncedPlugin = plugin;
  44980. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  44981. if (onsuccess) {
  44982. onsuccess(scene);
  44983. }
  44984. scene._removePendingData(loadingToken);
  44985. }, function () {
  44986. if (onerror) {
  44987. onerror(scene);
  44988. }
  44989. scene._removePendingData(loadingToken);
  44990. scene.getEngine().hideLoadingUI();
  44991. });
  44992. }
  44993. if (SceneLoader.ShowLoadingScreen) {
  44994. scene.executeWhenReady(function () {
  44995. scene.getEngine().hideLoadingUI();
  44996. });
  44997. }
  44998. };
  44999. var manifestChecked = function (success) {
  45000. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  45001. };
  45002. if (directLoad) {
  45003. loadSceneFromData(directLoad);
  45004. return;
  45005. }
  45006. if (rootUrl.indexOf("file:") === -1) {
  45007. if (scene.getEngine().enableOfflineSupport) {
  45008. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  45009. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  45010. }
  45011. else {
  45012. manifestChecked(true);
  45013. }
  45014. }
  45015. else {
  45016. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  45017. }
  45018. };
  45019. return SceneLoader;
  45020. }());
  45021. // Flags
  45022. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  45023. SceneLoader._ShowLoadingScreen = true;
  45024. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  45025. // Members
  45026. SceneLoader._registeredPlugins = {};
  45027. BABYLON.SceneLoader = SceneLoader;
  45028. ;
  45029. })(BABYLON || (BABYLON = {}));
  45030. //# sourceMappingURL=babylon.sceneLoader.js.map
  45031. var BABYLON;
  45032. (function (BABYLON) {
  45033. var Internals;
  45034. (function (Internals) {
  45035. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  45036. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45037. var parsedMaterial = parsedData.materials[index];
  45038. if (parsedMaterial.id === id) {
  45039. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45040. }
  45041. }
  45042. return null;
  45043. };
  45044. var isDescendantOf = function (mesh, names, hierarchyIds) {
  45045. names = (names instanceof Array) ? names : [names];
  45046. for (var i in names) {
  45047. if (mesh.name === names[i]) {
  45048. hierarchyIds.push(mesh.id);
  45049. return true;
  45050. }
  45051. }
  45052. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  45053. hierarchyIds.push(mesh.id);
  45054. return true;
  45055. }
  45056. return false;
  45057. };
  45058. var logOperation = function (operation, producer) {
  45059. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  45060. };
  45061. BABYLON.SceneLoader.RegisterPlugin({
  45062. extensions: ".babylon",
  45063. canDirectLoad: function (data) {
  45064. if (data.indexOf("babylon") !== -1) {
  45065. return true;
  45066. }
  45067. return false;
  45068. },
  45069. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  45070. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45071. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45072. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45073. // and avoid problems with multiple concurrent .babylon loads.
  45074. var log = "importMesh has failed JSON parse";
  45075. try {
  45076. var parsedData = JSON.parse(data);
  45077. log = "";
  45078. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45079. var loadedSkeletonsIds = [];
  45080. var loadedMaterialsIds = [];
  45081. var hierarchyIds = [];
  45082. var index;
  45083. var cache;
  45084. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45085. var parsedMesh = parsedData.meshes[index];
  45086. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  45087. if (meshesNames instanceof Array) {
  45088. // Remove found mesh name from list.
  45089. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  45090. }
  45091. //Geometry?
  45092. if (parsedMesh.geometryId) {
  45093. //does the file contain geometries?
  45094. if (parsedData.geometries) {
  45095. //find the correct geometry and add it to the scene
  45096. var found = false;
  45097. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  45098. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  45099. return;
  45100. }
  45101. else {
  45102. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  45103. if (parsedGeometryData.id === parsedMesh.geometryId) {
  45104. switch (geometryType) {
  45105. case "boxes":
  45106. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  45107. break;
  45108. case "spheres":
  45109. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  45110. break;
  45111. case "cylinders":
  45112. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  45113. break;
  45114. case "toruses":
  45115. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  45116. break;
  45117. case "grounds":
  45118. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  45119. break;
  45120. case "planes":
  45121. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  45122. break;
  45123. case "torusKnots":
  45124. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  45125. break;
  45126. case "vertexData":
  45127. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  45128. break;
  45129. }
  45130. found = true;
  45131. }
  45132. });
  45133. }
  45134. });
  45135. if (!found) {
  45136. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  45137. }
  45138. }
  45139. }
  45140. // Material ?
  45141. if (parsedMesh.materialId) {
  45142. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  45143. if (!materialFound && parsedData.multiMaterials) {
  45144. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  45145. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  45146. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  45147. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  45148. var subMatId = parsedMultiMaterial.materials[matIndex];
  45149. loadedMaterialsIds.push(subMatId);
  45150. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  45151. log += "\n\tMaterial " + mat.toString(fullDetails);
  45152. }
  45153. loadedMaterialsIds.push(parsedMultiMaterial.id);
  45154. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45155. materialFound = true;
  45156. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  45157. break;
  45158. }
  45159. }
  45160. }
  45161. if (!materialFound) {
  45162. loadedMaterialsIds.push(parsedMesh.materialId);
  45163. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  45164. if (!mat) {
  45165. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  45166. }
  45167. else {
  45168. log += "\n\tMaterial " + mat.toString(fullDetails);
  45169. }
  45170. }
  45171. }
  45172. // Skeleton ?
  45173. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  45174. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  45175. if (!skeletonAlreadyLoaded) {
  45176. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  45177. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  45178. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  45179. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45180. skeletons.push(skeleton);
  45181. loadedSkeletonsIds.push(parsedSkeleton.id);
  45182. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  45183. }
  45184. }
  45185. }
  45186. }
  45187. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45188. meshes.push(mesh);
  45189. log += "\n\tMesh " + mesh.toString(fullDetails);
  45190. }
  45191. }
  45192. // Connecting parents
  45193. var currentMesh;
  45194. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45195. currentMesh = scene.meshes[index];
  45196. if (currentMesh._waitingParentId) {
  45197. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  45198. currentMesh._waitingParentId = undefined;
  45199. }
  45200. }
  45201. // freeze and compute world matrix application
  45202. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45203. currentMesh = scene.meshes[index];
  45204. if (currentMesh._waitingFreezeWorldMatrix) {
  45205. currentMesh.freezeWorldMatrix();
  45206. currentMesh._waitingFreezeWorldMatrix = undefined;
  45207. }
  45208. else {
  45209. currentMesh.computeWorldMatrix(true);
  45210. }
  45211. }
  45212. // Particles
  45213. if (parsedData.particleSystems) {
  45214. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45215. var parsedParticleSystem = parsedData.particleSystems[index];
  45216. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  45217. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  45218. }
  45219. }
  45220. }
  45221. return true;
  45222. }
  45223. catch (err) {
  45224. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  45225. log = null;
  45226. throw err;
  45227. }
  45228. finally {
  45229. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45230. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45231. }
  45232. }
  45233. },
  45234. load: function (scene, data, rootUrl) {
  45235. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  45236. // when SceneLoader.debugLogging = true (default), or exception encountered.
  45237. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  45238. // and avoid problems with multiple concurrent .babylon loads.
  45239. var log = "importScene has failed JSON parse";
  45240. try {
  45241. var parsedData = JSON.parse(data);
  45242. log = "";
  45243. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  45244. // Scene
  45245. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  45246. scene.autoClear = parsedData.autoClear;
  45247. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  45248. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  45249. if (parsedData.gravity) {
  45250. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  45251. }
  45252. // Fog
  45253. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  45254. scene.fogMode = parsedData.fogMode;
  45255. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  45256. scene.fogStart = parsedData.fogStart;
  45257. scene.fogEnd = parsedData.fogEnd;
  45258. scene.fogDensity = parsedData.fogDensity;
  45259. log += "\tFog mode for scene: ";
  45260. switch (scene.fogMode) {
  45261. // getters not compiling, so using hardcoded
  45262. case 1:
  45263. log += "exp\n";
  45264. break;
  45265. case 2:
  45266. log += "exp2\n";
  45267. break;
  45268. case 3:
  45269. log += "linear\n";
  45270. break;
  45271. }
  45272. }
  45273. //Physics
  45274. if (parsedData.physicsEnabled) {
  45275. var physicsPlugin;
  45276. if (parsedData.physicsEngine === "cannon") {
  45277. physicsPlugin = new BABYLON.CannonJSPlugin();
  45278. }
  45279. else if (parsedData.physicsEngine === "oimo") {
  45280. physicsPlugin = new BABYLON.OimoJSPlugin();
  45281. }
  45282. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  45283. //else - default engine, which is currently oimo
  45284. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  45285. scene.enablePhysics(physicsGravity, physicsPlugin);
  45286. }
  45287. // Metadata
  45288. if (parsedData.metadata !== undefined) {
  45289. scene.metadata = parsedData.metadata;
  45290. }
  45291. //collisions, if defined. otherwise, default is true
  45292. if (parsedData.collisionsEnabled != undefined) {
  45293. scene.collisionsEnabled = parsedData.collisionsEnabled;
  45294. }
  45295. scene.workerCollisions = !!parsedData.workerCollisions;
  45296. var index;
  45297. var cache;
  45298. // Lights
  45299. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  45300. var parsedLight = parsedData.lights[index];
  45301. var light = BABYLON.Light.Parse(parsedLight, scene);
  45302. log += (index === 0 ? "\n\tLights:" : "");
  45303. log += "\n\t\t" + light.toString(fullDetails);
  45304. }
  45305. // Animations
  45306. if (parsedData.animations) {
  45307. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  45308. var parsedAnimation = parsedData.animations[index];
  45309. var animation = BABYLON.Animation.Parse(parsedAnimation);
  45310. scene.animations.push(animation);
  45311. log += (index === 0 ? "\n\tAnimations:" : "");
  45312. log += "\n\t\t" + animation.toString(fullDetails);
  45313. }
  45314. }
  45315. if (parsedData.autoAnimate) {
  45316. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  45317. }
  45318. // Materials
  45319. if (parsedData.materials) {
  45320. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  45321. var parsedMaterial = parsedData.materials[index];
  45322. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  45323. log += (index === 0 ? "\n\tMaterials:" : "");
  45324. log += "\n\t\t" + mat.toString(fullDetails);
  45325. }
  45326. }
  45327. if (parsedData.multiMaterials) {
  45328. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  45329. var parsedMultiMaterial = parsedData.multiMaterials[index];
  45330. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  45331. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  45332. log += "\n\t\t" + mmat.toString(fullDetails);
  45333. }
  45334. }
  45335. // Morph targets
  45336. if (parsedData.morphTargetManagers) {
  45337. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  45338. var managerData = _a[_i];
  45339. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  45340. }
  45341. }
  45342. // Skeletons
  45343. if (parsedData.skeletons) {
  45344. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  45345. var parsedSkeleton = parsedData.skeletons[index];
  45346. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  45347. log += (index === 0 ? "\n\tSkeletons:" : "");
  45348. log += "\n\t\t" + skeleton.toString(fullDetails);
  45349. }
  45350. }
  45351. // Geometries
  45352. var geometries = parsedData.geometries;
  45353. if (geometries) {
  45354. // Boxes
  45355. var boxes = geometries.boxes;
  45356. if (boxes) {
  45357. for (index = 0, cache = boxes.length; index < cache; index++) {
  45358. var parsedBox = boxes[index];
  45359. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  45360. }
  45361. }
  45362. // Spheres
  45363. var spheres = geometries.spheres;
  45364. if (spheres) {
  45365. for (index = 0, cache = spheres.length; index < cache; index++) {
  45366. var parsedSphere = spheres[index];
  45367. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  45368. }
  45369. }
  45370. // Cylinders
  45371. var cylinders = geometries.cylinders;
  45372. if (cylinders) {
  45373. for (index = 0, cache = cylinders.length; index < cache; index++) {
  45374. var parsedCylinder = cylinders[index];
  45375. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  45376. }
  45377. }
  45378. // Toruses
  45379. var toruses = geometries.toruses;
  45380. if (toruses) {
  45381. for (index = 0, cache = toruses.length; index < cache; index++) {
  45382. var parsedTorus = toruses[index];
  45383. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  45384. }
  45385. }
  45386. // Grounds
  45387. var grounds = geometries.grounds;
  45388. if (grounds) {
  45389. for (index = 0, cache = grounds.length; index < cache; index++) {
  45390. var parsedGround = grounds[index];
  45391. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  45392. }
  45393. }
  45394. // Planes
  45395. var planes = geometries.planes;
  45396. if (planes) {
  45397. for (index = 0, cache = planes.length; index < cache; index++) {
  45398. var parsedPlane = planes[index];
  45399. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  45400. }
  45401. }
  45402. // TorusKnots
  45403. var torusKnots = geometries.torusKnots;
  45404. if (torusKnots) {
  45405. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  45406. var parsedTorusKnot = torusKnots[index];
  45407. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  45408. }
  45409. }
  45410. // VertexData
  45411. var vertexData = geometries.vertexData;
  45412. if (vertexData) {
  45413. for (index = 0, cache = vertexData.length; index < cache; index++) {
  45414. var parsedVertexData = vertexData[index];
  45415. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  45416. }
  45417. }
  45418. }
  45419. // Meshes
  45420. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  45421. var parsedMesh = parsedData.meshes[index];
  45422. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  45423. log += (index === 0 ? "\n\tMeshes:" : "");
  45424. log += "\n\t\t" + mesh.toString(fullDetails);
  45425. }
  45426. // Cameras
  45427. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  45428. var parsedCamera = parsedData.cameras[index];
  45429. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  45430. log += (index === 0 ? "\n\tCameras:" : "");
  45431. log += "\n\t\t" + camera.toString(fullDetails);
  45432. }
  45433. if (parsedData.activeCameraID) {
  45434. scene.setActiveCameraByID(parsedData.activeCameraID);
  45435. }
  45436. // Browsing all the graph to connect the dots
  45437. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  45438. var camera = scene.cameras[index];
  45439. if (camera._waitingParentId) {
  45440. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  45441. camera._waitingParentId = undefined;
  45442. }
  45443. }
  45444. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45445. var light = scene.lights[index];
  45446. if (light._waitingParentId) {
  45447. light.parent = scene.getLastEntryByID(light._waitingParentId);
  45448. light._waitingParentId = undefined;
  45449. }
  45450. }
  45451. // Sounds
  45452. var loadedSounds = [];
  45453. var loadedSound;
  45454. if (BABYLON.AudioEngine && parsedData.sounds) {
  45455. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  45456. var parsedSound = parsedData.sounds[index];
  45457. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45458. if (!parsedSound.url)
  45459. parsedSound.url = parsedSound.name;
  45460. if (!loadedSounds[parsedSound.url]) {
  45461. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  45462. loadedSounds[parsedSound.url] = loadedSound;
  45463. }
  45464. else {
  45465. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  45466. }
  45467. }
  45468. else {
  45469. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  45470. }
  45471. }
  45472. }
  45473. loadedSounds = [];
  45474. // Connect parents & children and parse actions
  45475. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45476. var mesh = scene.meshes[index];
  45477. if (mesh._waitingParentId) {
  45478. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  45479. mesh._waitingParentId = undefined;
  45480. }
  45481. if (mesh._waitingActions) {
  45482. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  45483. mesh._waitingActions = undefined;
  45484. }
  45485. }
  45486. // freeze world matrix application
  45487. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  45488. var currentMesh = scene.meshes[index];
  45489. if (currentMesh._waitingFreezeWorldMatrix) {
  45490. currentMesh.freezeWorldMatrix();
  45491. currentMesh._waitingFreezeWorldMatrix = undefined;
  45492. }
  45493. else {
  45494. currentMesh.computeWorldMatrix(true);
  45495. }
  45496. }
  45497. // Particles Systems
  45498. if (parsedData.particleSystems) {
  45499. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  45500. var parsedParticleSystem = parsedData.particleSystems[index];
  45501. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  45502. }
  45503. }
  45504. // Lens flares
  45505. if (parsedData.lensFlareSystems) {
  45506. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  45507. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  45508. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  45509. }
  45510. }
  45511. // Shadows
  45512. if (parsedData.shadowGenerators) {
  45513. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  45514. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  45515. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  45516. }
  45517. }
  45518. // Lights exclusions / inclusions
  45519. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  45520. var light = scene.lights[index];
  45521. // Excluded check
  45522. if (light._excludedMeshesIds.length > 0) {
  45523. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  45524. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  45525. if (excludedMesh) {
  45526. light.excludedMeshes.push(excludedMesh);
  45527. }
  45528. }
  45529. light._excludedMeshesIds = [];
  45530. }
  45531. // Included check
  45532. if (light._includedOnlyMeshesIds.length > 0) {
  45533. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  45534. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  45535. if (includedOnlyMesh) {
  45536. light.includedOnlyMeshes.push(includedOnlyMesh);
  45537. }
  45538. }
  45539. light._includedOnlyMeshesIds = [];
  45540. }
  45541. }
  45542. // Actions (scene)
  45543. if (parsedData.actions) {
  45544. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  45545. }
  45546. // Finish
  45547. return true;
  45548. }
  45549. catch (err) {
  45550. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  45551. log = null;
  45552. throw err;
  45553. }
  45554. finally {
  45555. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  45556. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  45557. }
  45558. }
  45559. }
  45560. });
  45561. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45562. })(BABYLON || (BABYLON = {}));
  45563. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  45564. var BABYLON;
  45565. (function (BABYLON) {
  45566. var FilesInput = (function () {
  45567. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  45568. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  45569. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  45570. this._engine = p_engine;
  45571. this._canvas = p_canvas;
  45572. this._currentScene = p_scene;
  45573. this._sceneLoadedCallback = p_sceneLoadedCallback;
  45574. this._progressCallback = p_progressCallback;
  45575. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  45576. this._textureLoadingCallback = p_textureLoadingCallback;
  45577. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  45578. }
  45579. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  45580. var _this = this;
  45581. if (p_elementToMonitor) {
  45582. this._elementToMonitor = p_elementToMonitor;
  45583. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  45584. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  45585. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  45586. }
  45587. };
  45588. FilesInput.prototype.renderFunction = function () {
  45589. if (this._additionnalRenderLoopLogicCallback) {
  45590. this._additionnalRenderLoopLogicCallback();
  45591. }
  45592. if (this._currentScene) {
  45593. if (this._textureLoadingCallback) {
  45594. var remaining = this._currentScene.getWaitingItemsCount();
  45595. if (remaining > 0) {
  45596. this._textureLoadingCallback(remaining);
  45597. }
  45598. }
  45599. this._currentScene.render();
  45600. }
  45601. };
  45602. FilesInput.prototype.drag = function (e) {
  45603. e.stopPropagation();
  45604. e.preventDefault();
  45605. };
  45606. FilesInput.prototype.drop = function (eventDrop) {
  45607. eventDrop.stopPropagation();
  45608. eventDrop.preventDefault();
  45609. this.loadFiles(eventDrop);
  45610. };
  45611. FilesInput.prototype.loadFiles = function (event) {
  45612. if (this._startingProcessingFilesCallback)
  45613. this._startingProcessingFilesCallback();
  45614. // Handling data transfer via drag'n'drop
  45615. if (event && event.dataTransfer && event.dataTransfer.files) {
  45616. this._filesToLoad = event.dataTransfer.files;
  45617. }
  45618. // Handling files from input files
  45619. if (event && event.target && event.target.files) {
  45620. this._filesToLoad = event.target.files;
  45621. }
  45622. if (this._filesToLoad && this._filesToLoad.length > 0) {
  45623. for (var i = 0; i < this._filesToLoad.length; i++) {
  45624. var name_1 = this._filesToLoad[i].name.toLowerCase();
  45625. var extension = name_1.split('.').pop();
  45626. var type = this._filesToLoad[i].type;
  45627. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  45628. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  45629. this._sceneFileToLoad = this._filesToLoad[i];
  45630. }
  45631. else {
  45632. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  45633. }
  45634. }
  45635. this.reload();
  45636. }
  45637. };
  45638. FilesInput.prototype.reload = function () {
  45639. var _this = this;
  45640. var that = this;
  45641. // If a ".babylon" file has been provided
  45642. if (this._sceneFileToLoad) {
  45643. if (this._currentScene) {
  45644. if (BABYLON.Tools.errorsCount > 0) {
  45645. BABYLON.Tools.ClearLogCache();
  45646. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  45647. }
  45648. this._engine.stopRenderLoop();
  45649. this._currentScene.dispose();
  45650. }
  45651. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  45652. that._currentScene = newScene;
  45653. // Wait for textures and shaders to be ready
  45654. that._currentScene.executeWhenReady(function () {
  45655. if (that._sceneLoadedCallback) {
  45656. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  45657. }
  45658. that._engine.runRenderLoop(function () { that.renderFunction(); });
  45659. });
  45660. }, function (progress) {
  45661. if (_this._progressCallback) {
  45662. _this._progressCallback(progress);
  45663. }
  45664. });
  45665. }
  45666. else {
  45667. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  45668. }
  45669. };
  45670. return FilesInput;
  45671. }());
  45672. FilesInput.FilesToLoad = new Array();
  45673. BABYLON.FilesInput = FilesInput;
  45674. })(BABYLON || (BABYLON = {}));
  45675. //# sourceMappingURL=babylon.filesInput.js.map
  45676. var BABYLON;
  45677. (function (BABYLON) {
  45678. /**
  45679. * This class implement a typical dictionary using a string as key and the generic type T as value.
  45680. * The underlying implementation relies on an associative array to ensure the best performances.
  45681. * The value can be anything including 'null' but except 'undefined'
  45682. */
  45683. var StringDictionary = (function () {
  45684. function StringDictionary() {
  45685. this._count = 0;
  45686. this._data = {};
  45687. }
  45688. /**
  45689. * This will clear this dictionary and copy the content from the 'source' one.
  45690. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  45691. * @param source the dictionary to take the content from and copy to this dictionary
  45692. */
  45693. StringDictionary.prototype.copyFrom = function (source) {
  45694. var _this = this;
  45695. this.clear();
  45696. source.forEach(function (t, v) { return _this.add(t, v); });
  45697. };
  45698. /**
  45699. * Get a value based from its key
  45700. * @param key the given key to get the matching value from
  45701. * @return the value if found, otherwise undefined is returned
  45702. */
  45703. StringDictionary.prototype.get = function (key) {
  45704. var val = this._data[key];
  45705. if (val !== undefined) {
  45706. return val;
  45707. }
  45708. return undefined;
  45709. };
  45710. /**
  45711. * Get a value from its key or add it if it doesn't exist.
  45712. * This method will ensure you that a given key/data will be present in the dictionary.
  45713. * @param key the given key to get the matching value from
  45714. * @param factory the factory that will create the value if the key is not present in the dictionary.
  45715. * The factory will only be invoked if there's no data for the given key.
  45716. * @return the value corresponding to the key.
  45717. */
  45718. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  45719. var val = this.get(key);
  45720. if (val !== undefined) {
  45721. return val;
  45722. }
  45723. val = factory(key);
  45724. if (val) {
  45725. this.add(key, val);
  45726. }
  45727. return val;
  45728. };
  45729. /**
  45730. * Get a value from its key if present in the dictionary otherwise add it
  45731. * @param key the key to get the value from
  45732. * @param val if there's no such key/value pair in the dictionary add it with this value
  45733. * @return the value corresponding to the key
  45734. */
  45735. StringDictionary.prototype.getOrAdd = function (key, val) {
  45736. var curVal = this.get(key);
  45737. if (curVal !== undefined) {
  45738. return curVal;
  45739. }
  45740. this.add(key, val);
  45741. return val;
  45742. };
  45743. /**
  45744. * Check if there's a given key in the dictionary
  45745. * @param key the key to check for
  45746. * @return true if the key is present, false otherwise
  45747. */
  45748. StringDictionary.prototype.contains = function (key) {
  45749. return this._data[key] !== undefined;
  45750. };
  45751. /**
  45752. * Add a new key and its corresponding value
  45753. * @param key the key to add
  45754. * @param value the value corresponding to the key
  45755. * @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
  45756. */
  45757. StringDictionary.prototype.add = function (key, value) {
  45758. if (this._data[key] !== undefined) {
  45759. return false;
  45760. }
  45761. this._data[key] = value;
  45762. ++this._count;
  45763. return true;
  45764. };
  45765. StringDictionary.prototype.set = function (key, value) {
  45766. if (this._data[key] === undefined) {
  45767. return false;
  45768. }
  45769. this._data[key] = value;
  45770. return true;
  45771. };
  45772. /**
  45773. * Get the element of the given key and remove it from the dictionary
  45774. * @param key
  45775. */
  45776. StringDictionary.prototype.getAndRemove = function (key) {
  45777. var val = this.get(key);
  45778. if (val !== undefined) {
  45779. delete this._data[key];
  45780. --this._count;
  45781. return val;
  45782. }
  45783. return null;
  45784. };
  45785. /**
  45786. * Remove a key/value from the dictionary.
  45787. * @param key the key to remove
  45788. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  45789. */
  45790. StringDictionary.prototype.remove = function (key) {
  45791. if (this.contains(key)) {
  45792. delete this._data[key];
  45793. --this._count;
  45794. return true;
  45795. }
  45796. return false;
  45797. };
  45798. /**
  45799. * Clear the whole content of the dictionary
  45800. */
  45801. StringDictionary.prototype.clear = function () {
  45802. this._data = {};
  45803. this._count = 0;
  45804. };
  45805. Object.defineProperty(StringDictionary.prototype, "count", {
  45806. get: function () {
  45807. return this._count;
  45808. },
  45809. enumerable: true,
  45810. configurable: true
  45811. });
  45812. /**
  45813. * Execute a callback on each key/val of the dictionary.
  45814. * Note that you can remove any element in this dictionary in the callback implementation
  45815. * @param callback the callback to execute on a given key/value pair
  45816. */
  45817. StringDictionary.prototype.forEach = function (callback) {
  45818. for (var cur in this._data) {
  45819. var val = this._data[cur];
  45820. callback(cur, val);
  45821. }
  45822. };
  45823. /**
  45824. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  45825. * If the callback returns null or undefined the method will iterate to the next key/value pair
  45826. * Note that you can remove any element in this dictionary in the callback implementation
  45827. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  45828. */
  45829. StringDictionary.prototype.first = function (callback) {
  45830. for (var cur in this._data) {
  45831. var val = this._data[cur];
  45832. var res = callback(cur, val);
  45833. if (res) {
  45834. return res;
  45835. }
  45836. }
  45837. return null;
  45838. };
  45839. return StringDictionary;
  45840. }());
  45841. BABYLON.StringDictionary = StringDictionary;
  45842. })(BABYLON || (BABYLON = {}));
  45843. //# sourceMappingURL=babylon.stringDictionary.js.map
  45844. var BABYLON;
  45845. (function (BABYLON) {
  45846. var Tags = (function () {
  45847. function Tags() {
  45848. }
  45849. Tags.EnableFor = function (obj) {
  45850. obj._tags = obj._tags || {};
  45851. obj.hasTags = function () {
  45852. return Tags.HasTags(obj);
  45853. };
  45854. obj.addTags = function (tagsString) {
  45855. return Tags.AddTagsTo(obj, tagsString);
  45856. };
  45857. obj.removeTags = function (tagsString) {
  45858. return Tags.RemoveTagsFrom(obj, tagsString);
  45859. };
  45860. obj.matchesTagsQuery = function (tagsQuery) {
  45861. return Tags.MatchesQuery(obj, tagsQuery);
  45862. };
  45863. };
  45864. Tags.DisableFor = function (obj) {
  45865. delete obj._tags;
  45866. delete obj.hasTags;
  45867. delete obj.addTags;
  45868. delete obj.removeTags;
  45869. delete obj.matchesTagsQuery;
  45870. };
  45871. Tags.HasTags = function (obj) {
  45872. if (!obj._tags) {
  45873. return false;
  45874. }
  45875. return !BABYLON.Tools.IsEmpty(obj._tags);
  45876. };
  45877. Tags.GetTags = function (obj, asString) {
  45878. if (asString === void 0) { asString = true; }
  45879. if (!obj._tags) {
  45880. return null;
  45881. }
  45882. if (asString) {
  45883. var tagsArray = [];
  45884. for (var tag in obj._tags) {
  45885. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  45886. tagsArray.push(tag);
  45887. }
  45888. }
  45889. return tagsArray.join(" ");
  45890. }
  45891. else {
  45892. return obj._tags;
  45893. }
  45894. };
  45895. // the tags 'true' and 'false' are reserved and cannot be used as tags
  45896. // a tag cannot start with '||', '&&', and '!'
  45897. // it cannot contain whitespaces
  45898. Tags.AddTagsTo = function (obj, tagsString) {
  45899. if (!tagsString) {
  45900. return;
  45901. }
  45902. if (typeof tagsString !== "string") {
  45903. return;
  45904. }
  45905. var tags = tagsString.split(" ");
  45906. tags.forEach(function (tag, index, array) {
  45907. Tags._AddTagTo(obj, tag);
  45908. });
  45909. };
  45910. Tags._AddTagTo = function (obj, tag) {
  45911. tag = tag.trim();
  45912. if (tag === "" || tag === "true" || tag === "false") {
  45913. return;
  45914. }
  45915. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  45916. return;
  45917. }
  45918. Tags.EnableFor(obj);
  45919. obj._tags[tag] = true;
  45920. };
  45921. Tags.RemoveTagsFrom = function (obj, tagsString) {
  45922. if (!Tags.HasTags(obj)) {
  45923. return;
  45924. }
  45925. var tags = tagsString.split(" ");
  45926. for (var t in tags) {
  45927. Tags._RemoveTagFrom(obj, tags[t]);
  45928. }
  45929. };
  45930. Tags._RemoveTagFrom = function (obj, tag) {
  45931. delete obj._tags[tag];
  45932. };
  45933. Tags.MatchesQuery = function (obj, tagsQuery) {
  45934. if (tagsQuery === undefined) {
  45935. return true;
  45936. }
  45937. if (tagsQuery === "") {
  45938. return Tags.HasTags(obj);
  45939. }
  45940. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  45941. };
  45942. return Tags;
  45943. }());
  45944. BABYLON.Tags = Tags;
  45945. })(BABYLON || (BABYLON = {}));
  45946. //# sourceMappingURL=babylon.tags.js.map
  45947. var BABYLON;
  45948. (function (BABYLON) {
  45949. var Internals;
  45950. (function (Internals) {
  45951. var AndOrNotEvaluator = (function () {
  45952. function AndOrNotEvaluator() {
  45953. }
  45954. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  45955. if (!query.match(/\([^\(\)]*\)/g)) {
  45956. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  45957. }
  45958. else {
  45959. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  45960. // remove parenthesis
  45961. r = r.slice(1, r.length - 1);
  45962. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  45963. });
  45964. }
  45965. if (query === "true") {
  45966. return true;
  45967. }
  45968. if (query === "false") {
  45969. return false;
  45970. }
  45971. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  45972. };
  45973. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  45974. evaluateCallback = evaluateCallback || (function (r) {
  45975. return r === "true" ? true : false;
  45976. });
  45977. var result;
  45978. var or = parenthesisContent.split("||");
  45979. for (var i in or) {
  45980. if (or.hasOwnProperty(i)) {
  45981. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  45982. var and = ori.split("&&");
  45983. if (and.length > 1) {
  45984. for (var j = 0; j < and.length; ++j) {
  45985. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  45986. if (andj !== "true" && andj !== "false") {
  45987. if (andj[0] === "!") {
  45988. result = !evaluateCallback(andj.substring(1));
  45989. }
  45990. else {
  45991. result = evaluateCallback(andj);
  45992. }
  45993. }
  45994. else {
  45995. result = andj === "true" ? true : false;
  45996. }
  45997. if (!result) {
  45998. ori = "false";
  45999. break;
  46000. }
  46001. }
  46002. }
  46003. if (result || ori === "true") {
  46004. result = true;
  46005. break;
  46006. }
  46007. // result equals false (or undefined)
  46008. if (ori !== "true" && ori !== "false") {
  46009. if (ori[0] === "!") {
  46010. result = !evaluateCallback(ori.substring(1));
  46011. }
  46012. else {
  46013. result = evaluateCallback(ori);
  46014. }
  46015. }
  46016. else {
  46017. result = ori === "true" ? true : false;
  46018. }
  46019. }
  46020. }
  46021. // the whole parenthesis scope is replaced by 'true' or 'false'
  46022. return result ? "true" : "false";
  46023. };
  46024. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  46025. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  46026. // remove whitespaces
  46027. r = r.replace(/[\s]/g, function () { return ""; });
  46028. return r.length % 2 ? "!" : "";
  46029. });
  46030. booleanString = booleanString.trim();
  46031. if (booleanString === "!true") {
  46032. booleanString = "false";
  46033. }
  46034. else if (booleanString === "!false") {
  46035. booleanString = "true";
  46036. }
  46037. return booleanString;
  46038. };
  46039. return AndOrNotEvaluator;
  46040. }());
  46041. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  46042. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46043. })(BABYLON || (BABYLON = {}));
  46044. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  46045. var BABYLON;
  46046. (function (BABYLON) {
  46047. var Database = (function () {
  46048. function Database(urlToScene, callbackManifestChecked) {
  46049. // Handling various flavors of prefixed version of IndexedDB
  46050. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  46051. this.callbackManifestChecked = callbackManifestChecked;
  46052. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  46053. this.db = null;
  46054. this.enableSceneOffline = false;
  46055. this.enableTexturesOffline = false;
  46056. this.manifestVersionFound = 0;
  46057. this.mustUpdateRessources = false;
  46058. this.hasReachedQuota = false;
  46059. if (!Database.IDBStorageEnabled) {
  46060. this.callbackManifestChecked(true);
  46061. }
  46062. else {
  46063. this.checkManifestFile();
  46064. }
  46065. }
  46066. Database.prototype.checkManifestFile = function () {
  46067. var _this = this;
  46068. function noManifestFile() {
  46069. that.enableSceneOffline = false;
  46070. that.enableTexturesOffline = false;
  46071. that.callbackManifestChecked(false);
  46072. }
  46073. var that = this;
  46074. var timeStampUsed = false;
  46075. var manifestURL = this.currentSceneUrl + ".manifest";
  46076. var xhr = new XMLHttpRequest();
  46077. if (navigator.onLine) {
  46078. // Adding a timestamp to by-pass browsers' cache
  46079. timeStampUsed = true;
  46080. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  46081. }
  46082. xhr.open("GET", manifestURL, true);
  46083. xhr.addEventListener("load", function () {
  46084. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  46085. try {
  46086. var manifestFile = JSON.parse(xhr.response);
  46087. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  46088. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  46089. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  46090. _this.manifestVersionFound = manifestFile.version;
  46091. }
  46092. if (_this.callbackManifestChecked) {
  46093. _this.callbackManifestChecked(true);
  46094. }
  46095. }
  46096. catch (ex) {
  46097. noManifestFile();
  46098. }
  46099. }
  46100. else {
  46101. noManifestFile();
  46102. }
  46103. }, false);
  46104. xhr.addEventListener("error", function (event) {
  46105. if (timeStampUsed) {
  46106. timeStampUsed = false;
  46107. // Let's retry without the timeStamp
  46108. // It could fail when coupled with HTML5 Offline API
  46109. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  46110. xhr.open("GET", retryManifestURL, true);
  46111. xhr.send();
  46112. }
  46113. else {
  46114. noManifestFile();
  46115. }
  46116. }, false);
  46117. try {
  46118. xhr.send();
  46119. }
  46120. catch (ex) {
  46121. BABYLON.Tools.Error("Error on XHR send request.");
  46122. that.callbackManifestChecked(false);
  46123. }
  46124. };
  46125. Database.prototype.openAsync = function (successCallback, errorCallback) {
  46126. var _this = this;
  46127. function handleError() {
  46128. that.isSupported = false;
  46129. if (errorCallback)
  46130. errorCallback();
  46131. }
  46132. var that = this;
  46133. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  46134. // Your browser doesn't support IndexedDB
  46135. this.isSupported = false;
  46136. if (errorCallback)
  46137. errorCallback();
  46138. }
  46139. else {
  46140. // If the DB hasn't been opened or created yet
  46141. if (!this.db) {
  46142. this.hasReachedQuota = false;
  46143. this.isSupported = true;
  46144. var request = this.idbFactory.open("babylonjs", 1);
  46145. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  46146. request.onerror = function (event) {
  46147. handleError();
  46148. };
  46149. // executes when a version change transaction cannot complete due to other active transactions
  46150. request.onblocked = function (event) {
  46151. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  46152. handleError();
  46153. };
  46154. // DB has been opened successfully
  46155. request.onsuccess = function (event) {
  46156. _this.db = request.result;
  46157. successCallback();
  46158. };
  46159. // Initialization of the DB. Creating Scenes & Textures stores
  46160. request.onupgradeneeded = function (event) {
  46161. _this.db = (event.target).result;
  46162. try {
  46163. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  46164. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  46165. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  46166. }
  46167. catch (ex) {
  46168. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  46169. handleError();
  46170. }
  46171. };
  46172. }
  46173. else {
  46174. if (successCallback)
  46175. successCallback();
  46176. }
  46177. }
  46178. };
  46179. Database.prototype.loadImageFromDB = function (url, image) {
  46180. var _this = this;
  46181. var completeURL = Database.ReturnFullUrlLocation(url);
  46182. var saveAndLoadImage = function () {
  46183. if (!_this.hasReachedQuota && _this.db !== null) {
  46184. // the texture is not yet in the DB, let's try to save it
  46185. _this._saveImageIntoDBAsync(completeURL, image);
  46186. }
  46187. else {
  46188. image.src = url;
  46189. }
  46190. };
  46191. if (!this.mustUpdateRessources) {
  46192. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  46193. }
  46194. else {
  46195. saveAndLoadImage();
  46196. }
  46197. };
  46198. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  46199. if (this.isSupported && this.db !== null) {
  46200. var texture;
  46201. var transaction = this.db.transaction(["textures"]);
  46202. transaction.onabort = function (event) {
  46203. image.src = url;
  46204. };
  46205. transaction.oncomplete = function (event) {
  46206. var blobTextureURL;
  46207. if (texture) {
  46208. var URL = window.URL || window.webkitURL;
  46209. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  46210. image.onerror = function () {
  46211. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  46212. image.src = url;
  46213. };
  46214. image.src = blobTextureURL;
  46215. }
  46216. else {
  46217. notInDBCallback();
  46218. }
  46219. };
  46220. var getRequest = transaction.objectStore("textures").get(url);
  46221. getRequest.onsuccess = function (event) {
  46222. texture = (event.target).result;
  46223. };
  46224. getRequest.onerror = function (event) {
  46225. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  46226. image.src = url;
  46227. };
  46228. }
  46229. else {
  46230. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46231. image.src = url;
  46232. }
  46233. };
  46234. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  46235. var _this = this;
  46236. if (this.isSupported) {
  46237. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  46238. var generateBlobUrl = function () {
  46239. var blobTextureURL;
  46240. if (blob) {
  46241. var URL = window.URL || window.webkitURL;
  46242. try {
  46243. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  46244. }
  46245. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  46246. catch (ex) {
  46247. blobTextureURL = URL.createObjectURL(blob);
  46248. }
  46249. }
  46250. image.src = blobTextureURL;
  46251. };
  46252. if (Database.IsUASupportingBlobStorage) {
  46253. var xhr = new XMLHttpRequest(), blob;
  46254. xhr.open("GET", url, true);
  46255. xhr.responseType = "blob";
  46256. xhr.addEventListener("load", function () {
  46257. if (xhr.status === 200) {
  46258. // Blob as response (XHR2)
  46259. blob = xhr.response;
  46260. var transaction = _this.db.transaction(["textures"], "readwrite");
  46261. // the transaction could abort because of a QuotaExceededError error
  46262. transaction.onabort = function (event) {
  46263. try {
  46264. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46265. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46266. _this.hasReachedQuota = true;
  46267. }
  46268. }
  46269. catch (ex) { }
  46270. generateBlobUrl();
  46271. };
  46272. transaction.oncomplete = function (event) {
  46273. generateBlobUrl();
  46274. };
  46275. var newTexture = { textureUrl: url, data: blob };
  46276. try {
  46277. // Put the blob into the dabase
  46278. var addRequest = transaction.objectStore("textures").put(newTexture);
  46279. addRequest.onsuccess = function (event) {
  46280. };
  46281. addRequest.onerror = function (event) {
  46282. generateBlobUrl();
  46283. };
  46284. }
  46285. catch (ex) {
  46286. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  46287. if (ex.code === 25) {
  46288. Database.IsUASupportingBlobStorage = false;
  46289. }
  46290. image.src = url;
  46291. }
  46292. }
  46293. else {
  46294. image.src = url;
  46295. }
  46296. }, false);
  46297. xhr.addEventListener("error", function (event) {
  46298. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  46299. image.src = url;
  46300. }, false);
  46301. xhr.send();
  46302. }
  46303. else {
  46304. image.src = url;
  46305. }
  46306. }
  46307. else {
  46308. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46309. image.src = url;
  46310. }
  46311. };
  46312. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  46313. var _this = this;
  46314. var updateVersion = function (event) {
  46315. // the version is not yet in the DB or we need to update it
  46316. _this._saveVersionIntoDBAsync(url, versionLoaded);
  46317. };
  46318. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  46319. };
  46320. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  46321. var _this = this;
  46322. if (this.isSupported) {
  46323. var version;
  46324. try {
  46325. var transaction = this.db.transaction(["versions"]);
  46326. transaction.oncomplete = function (event) {
  46327. if (version) {
  46328. // If the version in the JSON file is > than the version in DB
  46329. if (_this.manifestVersionFound > version.data) {
  46330. _this.mustUpdateRessources = true;
  46331. updateInDBCallback();
  46332. }
  46333. else {
  46334. callback(version.data);
  46335. }
  46336. }
  46337. else {
  46338. _this.mustUpdateRessources = true;
  46339. updateInDBCallback();
  46340. }
  46341. };
  46342. transaction.onabort = function (event) {
  46343. callback(-1);
  46344. };
  46345. var getRequest = transaction.objectStore("versions").get(url);
  46346. getRequest.onsuccess = function (event) {
  46347. version = (event.target).result;
  46348. };
  46349. getRequest.onerror = function (event) {
  46350. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  46351. callback(-1);
  46352. };
  46353. }
  46354. catch (ex) {
  46355. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  46356. callback(-1);
  46357. }
  46358. }
  46359. else {
  46360. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46361. callback(-1);
  46362. }
  46363. };
  46364. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  46365. var _this = this;
  46366. if (this.isSupported && !this.hasReachedQuota) {
  46367. try {
  46368. // Open a transaction to the database
  46369. var transaction = this.db.transaction(["versions"], "readwrite");
  46370. // the transaction could abort because of a QuotaExceededError error
  46371. transaction.onabort = function (event) {
  46372. try {
  46373. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46374. _this.hasReachedQuota = true;
  46375. }
  46376. }
  46377. catch (ex) { }
  46378. callback(-1);
  46379. };
  46380. transaction.oncomplete = function (event) {
  46381. callback(_this.manifestVersionFound);
  46382. };
  46383. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  46384. // Put the scene into the database
  46385. var addRequest = transaction.objectStore("versions").put(newVersion);
  46386. addRequest.onsuccess = function (event) {
  46387. };
  46388. addRequest.onerror = function (event) {
  46389. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  46390. };
  46391. }
  46392. catch (ex) {
  46393. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  46394. callback(-1);
  46395. }
  46396. }
  46397. else {
  46398. callback(-1);
  46399. }
  46400. };
  46401. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  46402. var _this = this;
  46403. var completeUrl = Database.ReturnFullUrlLocation(url);
  46404. var saveAndLoadFile = function (event) {
  46405. // the scene is not yet in the DB, let's try to save it
  46406. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  46407. };
  46408. this._checkVersionFromDB(completeUrl, function (version) {
  46409. if (version !== -1) {
  46410. if (!_this.mustUpdateRessources) {
  46411. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  46412. }
  46413. else {
  46414. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  46415. }
  46416. }
  46417. else {
  46418. errorCallback();
  46419. }
  46420. });
  46421. };
  46422. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  46423. if (this.isSupported) {
  46424. var targetStore;
  46425. if (url.indexOf(".babylon") !== -1) {
  46426. targetStore = "scenes";
  46427. }
  46428. else {
  46429. targetStore = "textures";
  46430. }
  46431. var file;
  46432. var transaction = this.db.transaction([targetStore]);
  46433. transaction.oncomplete = function (event) {
  46434. if (file) {
  46435. callback(file.data);
  46436. }
  46437. else {
  46438. notInDBCallback();
  46439. }
  46440. };
  46441. transaction.onabort = function (event) {
  46442. notInDBCallback();
  46443. };
  46444. var getRequest = transaction.objectStore(targetStore).get(url);
  46445. getRequest.onsuccess = function (event) {
  46446. file = (event.target).result;
  46447. };
  46448. getRequest.onerror = function (event) {
  46449. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  46450. notInDBCallback();
  46451. };
  46452. }
  46453. else {
  46454. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46455. callback();
  46456. }
  46457. };
  46458. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  46459. var _this = this;
  46460. if (this.isSupported) {
  46461. var targetStore;
  46462. if (url.indexOf(".babylon") !== -1) {
  46463. targetStore = "scenes";
  46464. }
  46465. else {
  46466. targetStore = "textures";
  46467. }
  46468. // Create XHR
  46469. var xhr = new XMLHttpRequest(), fileData;
  46470. xhr.open("GET", url, true);
  46471. if (useArrayBuffer) {
  46472. xhr.responseType = "arraybuffer";
  46473. }
  46474. xhr.onprogress = progressCallback;
  46475. xhr.addEventListener("load", function () {
  46476. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  46477. // Blob as response (XHR2)
  46478. //fileData = xhr.responseText;
  46479. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  46480. if (!_this.hasReachedQuota) {
  46481. // Open a transaction to the database
  46482. var transaction = _this.db.transaction([targetStore], "readwrite");
  46483. // the transaction could abort because of a QuotaExceededError error
  46484. transaction.onabort = function (event) {
  46485. try {
  46486. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  46487. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  46488. _this.hasReachedQuota = true;
  46489. }
  46490. }
  46491. catch (ex) { }
  46492. callback(fileData);
  46493. };
  46494. transaction.oncomplete = function (event) {
  46495. callback(fileData);
  46496. };
  46497. var newFile;
  46498. if (targetStore === "scenes") {
  46499. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  46500. }
  46501. else {
  46502. newFile = { textureUrl: url, data: fileData };
  46503. }
  46504. try {
  46505. // Put the scene into the database
  46506. var addRequest = transaction.objectStore(targetStore).put(newFile);
  46507. addRequest.onsuccess = function (event) {
  46508. };
  46509. addRequest.onerror = function (event) {
  46510. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  46511. };
  46512. }
  46513. catch (ex) {
  46514. callback(fileData);
  46515. }
  46516. }
  46517. else {
  46518. callback(fileData);
  46519. }
  46520. }
  46521. else {
  46522. callback();
  46523. }
  46524. }, false);
  46525. xhr.addEventListener("error", function (event) {
  46526. BABYLON.Tools.Error("error on XHR request.");
  46527. callback();
  46528. }, false);
  46529. xhr.send();
  46530. }
  46531. else {
  46532. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  46533. callback();
  46534. }
  46535. };
  46536. return Database;
  46537. }());
  46538. Database.IsUASupportingBlobStorage = true;
  46539. Database.IDBStorageEnabled = true;
  46540. Database.parseURL = function (url) {
  46541. var a = document.createElement('a');
  46542. a.href = url;
  46543. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  46544. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  46545. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  46546. return absLocation;
  46547. };
  46548. Database.ReturnFullUrlLocation = function (url) {
  46549. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  46550. return (Database.parseURL(window.location.href) + url);
  46551. }
  46552. else {
  46553. return url;
  46554. }
  46555. };
  46556. BABYLON.Database = Database;
  46557. })(BABYLON || (BABYLON = {}));
  46558. //# sourceMappingURL=babylon.database.js.map
  46559. var BABYLON;
  46560. (function (BABYLON) {
  46561. var FresnelParameters = (function () {
  46562. function FresnelParameters() {
  46563. this._isEnabled = true;
  46564. this.leftColor = BABYLON.Color3.White();
  46565. this.rightColor = BABYLON.Color3.Black();
  46566. this.bias = 0;
  46567. this.power = 1;
  46568. }
  46569. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  46570. get: function () {
  46571. return this._isEnabled;
  46572. },
  46573. set: function (value) {
  46574. if (this._isEnabled === value) {
  46575. return;
  46576. }
  46577. this._isEnabled = value;
  46578. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  46579. },
  46580. enumerable: true,
  46581. configurable: true
  46582. });
  46583. FresnelParameters.prototype.clone = function () {
  46584. var newFresnelParameters = new FresnelParameters();
  46585. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  46586. return newFresnelParameters;
  46587. };
  46588. FresnelParameters.prototype.serialize = function () {
  46589. var serializationObject = {};
  46590. serializationObject.isEnabled = this.isEnabled;
  46591. serializationObject.leftColor = this.leftColor;
  46592. serializationObject.rightColor = this.rightColor;
  46593. serializationObject.bias = this.bias;
  46594. serializationObject.power = this.power;
  46595. return serializationObject;
  46596. };
  46597. FresnelParameters.Parse = function (parsedFresnelParameters) {
  46598. var fresnelParameters = new FresnelParameters();
  46599. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  46600. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  46601. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  46602. fresnelParameters.bias = parsedFresnelParameters.bias;
  46603. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  46604. return fresnelParameters;
  46605. };
  46606. return FresnelParameters;
  46607. }());
  46608. BABYLON.FresnelParameters = FresnelParameters;
  46609. })(BABYLON || (BABYLON = {}));
  46610. //# sourceMappingURL=babylon.fresnelParameters.js.map
  46611. var BABYLON;
  46612. (function (BABYLON) {
  46613. var MultiMaterial = (function (_super) {
  46614. __extends(MultiMaterial, _super);
  46615. function MultiMaterial(name, scene) {
  46616. var _this = _super.call(this, name, scene, true) || this;
  46617. _this.subMaterials = new Array();
  46618. scene.multiMaterials.push(_this);
  46619. return _this;
  46620. }
  46621. // Properties
  46622. MultiMaterial.prototype.getSubMaterial = function (index) {
  46623. if (index < 0 || index >= this.subMaterials.length) {
  46624. return this.getScene().defaultMaterial;
  46625. }
  46626. return this.subMaterials[index];
  46627. };
  46628. // Methods
  46629. MultiMaterial.prototype.getClassName = function () {
  46630. return "MultiMaterial";
  46631. };
  46632. MultiMaterial.prototype.isReady = function (mesh) {
  46633. for (var index = 0; index < this.subMaterials.length; index++) {
  46634. var subMaterial = this.subMaterials[index];
  46635. if (subMaterial) {
  46636. if (!this.subMaterials[index].isReady(mesh)) {
  46637. return false;
  46638. }
  46639. }
  46640. }
  46641. return true;
  46642. };
  46643. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  46644. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  46645. for (var index = 0; index < this.subMaterials.length; index++) {
  46646. var subMaterial = null;
  46647. if (cloneChildren) {
  46648. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  46649. }
  46650. else {
  46651. subMaterial = this.subMaterials[index];
  46652. }
  46653. newMultiMaterial.subMaterials.push(subMaterial);
  46654. }
  46655. return newMultiMaterial;
  46656. };
  46657. MultiMaterial.prototype.serialize = function () {
  46658. var serializationObject = {};
  46659. serializationObject.name = this.name;
  46660. serializationObject.id = this.id;
  46661. serializationObject.tags = BABYLON.Tags.GetTags(this);
  46662. serializationObject.materials = [];
  46663. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  46664. var subMat = this.subMaterials[matIndex];
  46665. if (subMat) {
  46666. serializationObject.materials.push(subMat.id);
  46667. }
  46668. else {
  46669. serializationObject.materials.push(null);
  46670. }
  46671. }
  46672. return serializationObject;
  46673. };
  46674. return MultiMaterial;
  46675. }(BABYLON.Material));
  46676. BABYLON.MultiMaterial = MultiMaterial;
  46677. })(BABYLON || (BABYLON = {}));
  46678. //# sourceMappingURL=babylon.multiMaterial.js.map
  46679. var BABYLON;
  46680. (function (BABYLON) {
  46681. var FreeCameraTouchInput = (function () {
  46682. function FreeCameraTouchInput() {
  46683. this._offsetX = null;
  46684. this._offsetY = null;
  46685. this._pointerCount = 0;
  46686. this._pointerPressed = [];
  46687. this.touchAngularSensibility = 200000.0;
  46688. this.touchMoveSensibility = 250.0;
  46689. }
  46690. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  46691. var _this = this;
  46692. var previousPosition;
  46693. if (this._pointerInput === undefined) {
  46694. this._onLostFocus = function (evt) {
  46695. _this._offsetX = null;
  46696. _this._offsetY = null;
  46697. };
  46698. this._pointerInput = function (p, s) {
  46699. var evt = p.event;
  46700. if (evt.pointerType === "mouse") {
  46701. return;
  46702. }
  46703. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  46704. if (!noPreventDefault) {
  46705. evt.preventDefault();
  46706. }
  46707. _this._pointerPressed.push(evt.pointerId);
  46708. if (_this._pointerPressed.length !== 1) {
  46709. return;
  46710. }
  46711. previousPosition = {
  46712. x: evt.clientX,
  46713. y: evt.clientY
  46714. };
  46715. }
  46716. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  46717. if (!noPreventDefault) {
  46718. evt.preventDefault();
  46719. }
  46720. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46721. if (index === -1) {
  46722. return;
  46723. }
  46724. _this._pointerPressed.splice(index, 1);
  46725. if (index != 0) {
  46726. return;
  46727. }
  46728. previousPosition = null;
  46729. _this._offsetX = null;
  46730. _this._offsetY = null;
  46731. }
  46732. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46733. if (!noPreventDefault) {
  46734. evt.preventDefault();
  46735. }
  46736. if (!previousPosition) {
  46737. return;
  46738. }
  46739. var index = _this._pointerPressed.indexOf(evt.pointerId);
  46740. if (index != 0) {
  46741. return;
  46742. }
  46743. _this._offsetX = evt.clientX - previousPosition.x;
  46744. _this._offsetY = -(evt.clientY - previousPosition.y);
  46745. }
  46746. };
  46747. }
  46748. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46749. element.addEventListener("blur", this._onLostFocus);
  46750. };
  46751. FreeCameraTouchInput.prototype.detachControl = function (element) {
  46752. if (this._pointerInput && element) {
  46753. this.camera.getScene().onPointerObservable.remove(this._observer);
  46754. this._observer = null;
  46755. element.removeEventListener("blur", this._onLostFocus);
  46756. this._onLostFocus = null;
  46757. this._pointerPressed = [];
  46758. this._offsetX = null;
  46759. this._offsetY = null;
  46760. this._pointerCount = 0;
  46761. }
  46762. };
  46763. FreeCameraTouchInput.prototype.checkInputs = function () {
  46764. if (this._offsetX) {
  46765. var camera = this.camera;
  46766. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  46767. if (this._pointerPressed.length > 1) {
  46768. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  46769. }
  46770. else {
  46771. var speed = camera._computeLocalCameraSpeed();
  46772. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  46773. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  46774. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  46775. }
  46776. }
  46777. };
  46778. FreeCameraTouchInput.prototype.getTypeName = function () {
  46779. return "FreeCameraTouchInput";
  46780. };
  46781. FreeCameraTouchInput.prototype.getSimpleName = function () {
  46782. return "touch";
  46783. };
  46784. return FreeCameraTouchInput;
  46785. }());
  46786. __decorate([
  46787. BABYLON.serialize()
  46788. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  46789. __decorate([
  46790. BABYLON.serialize()
  46791. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  46792. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  46793. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  46794. })(BABYLON || (BABYLON = {}));
  46795. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  46796. /// <reference path="babylon.freeCamera.ts" />
  46797. var BABYLON;
  46798. (function (BABYLON) {
  46799. // We're mainly based on the logic defined into the FreeCamera code
  46800. var TouchCamera = (function (_super) {
  46801. __extends(TouchCamera, _super);
  46802. //-- end properties for backward compatibility for inputs
  46803. function TouchCamera(name, position, scene) {
  46804. var _this = _super.call(this, name, position, scene) || this;
  46805. _this.inputs.addTouch();
  46806. _this._setupInputs();
  46807. return _this;
  46808. }
  46809. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  46810. //-- Begin properties for backward compatibility for inputs
  46811. get: function () {
  46812. var touch = this.inputs.attached["touch"];
  46813. if (touch)
  46814. return touch.touchAngularSensibility;
  46815. },
  46816. set: function (value) {
  46817. var touch = this.inputs.attached["touch"];
  46818. if (touch)
  46819. touch.touchAngularSensibility = value;
  46820. },
  46821. enumerable: true,
  46822. configurable: true
  46823. });
  46824. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  46825. get: function () {
  46826. var touch = this.inputs.attached["touch"];
  46827. if (touch)
  46828. return touch.touchMoveSensibility;
  46829. },
  46830. set: function (value) {
  46831. var touch = this.inputs.attached["touch"];
  46832. if (touch)
  46833. touch.touchMoveSensibility = value;
  46834. },
  46835. enumerable: true,
  46836. configurable: true
  46837. });
  46838. TouchCamera.prototype.getClassName = function () {
  46839. return "TouchCamera";
  46840. };
  46841. TouchCamera.prototype._setupInputs = function () {
  46842. var mouse = this.inputs.attached["mouse"];
  46843. if (mouse) {
  46844. mouse.touchEnabled = false;
  46845. }
  46846. };
  46847. return TouchCamera;
  46848. }(BABYLON.FreeCamera));
  46849. BABYLON.TouchCamera = TouchCamera;
  46850. })(BABYLON || (BABYLON = {}));
  46851. //# sourceMappingURL=babylon.touchCamera.js.map
  46852. var BABYLON;
  46853. (function (BABYLON) {
  46854. var ProceduralTexture = (function (_super) {
  46855. __extends(ProceduralTexture, _super);
  46856. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  46857. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46858. if (isCube === void 0) { isCube = false; }
  46859. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  46860. _this.isCube = isCube;
  46861. _this.isEnabled = true;
  46862. _this._currentRefreshId = -1;
  46863. _this._refreshRate = 1;
  46864. _this._vertexBuffers = {};
  46865. _this._uniforms = new Array();
  46866. _this._samplers = new Array();
  46867. _this._textures = new Array();
  46868. _this._floats = new Array();
  46869. _this._floatsArrays = {};
  46870. _this._colors3 = new Array();
  46871. _this._colors4 = new Array();
  46872. _this._vectors2 = new Array();
  46873. _this._vectors3 = new Array();
  46874. _this._matrices = new Array();
  46875. _this._fallbackTextureUsed = false;
  46876. scene._proceduralTextures.push(_this);
  46877. _this.name = name;
  46878. _this.isRenderTarget = true;
  46879. _this._size = size;
  46880. _this._generateMipMaps = generateMipMaps;
  46881. _this.setFragment(fragment);
  46882. _this._fallbackTexture = fallbackTexture;
  46883. var engine = scene.getEngine();
  46884. if (isCube) {
  46885. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  46886. _this.setFloat("face", 0);
  46887. }
  46888. else {
  46889. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  46890. }
  46891. // VBO
  46892. var vertices = [];
  46893. vertices.push(1, 1);
  46894. vertices.push(-1, 1);
  46895. vertices.push(-1, -1);
  46896. vertices.push(1, -1);
  46897. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46898. // Indices
  46899. var indices = [];
  46900. indices.push(0);
  46901. indices.push(1);
  46902. indices.push(2);
  46903. indices.push(0);
  46904. indices.push(2);
  46905. indices.push(3);
  46906. _this._indexBuffer = engine.createIndexBuffer(indices);
  46907. return _this;
  46908. }
  46909. ProceduralTexture.prototype.reset = function () {
  46910. if (this._effect === undefined) {
  46911. return;
  46912. }
  46913. var engine = this.getScene().getEngine();
  46914. engine._releaseEffect(this._effect);
  46915. };
  46916. ProceduralTexture.prototype.isReady = function () {
  46917. var _this = this;
  46918. var engine = this.getScene().getEngine();
  46919. var shaders;
  46920. if (!this._fragment) {
  46921. return false;
  46922. }
  46923. if (this._fallbackTextureUsed) {
  46924. return true;
  46925. }
  46926. if (this._fragment.fragmentElement !== undefined) {
  46927. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  46928. }
  46929. else {
  46930. shaders = { vertex: "procedural", fragment: this._fragment };
  46931. }
  46932. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  46933. _this.releaseInternalTexture();
  46934. if (_this._fallbackTexture) {
  46935. _this._texture = _this._fallbackTexture._texture;
  46936. _this._texture.references++;
  46937. }
  46938. _this._fallbackTextureUsed = true;
  46939. });
  46940. return this._effect.isReady();
  46941. };
  46942. ProceduralTexture.prototype.resetRefreshCounter = function () {
  46943. this._currentRefreshId = -1;
  46944. };
  46945. ProceduralTexture.prototype.setFragment = function (fragment) {
  46946. this._fragment = fragment;
  46947. };
  46948. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  46949. get: function () {
  46950. return this._refreshRate;
  46951. },
  46952. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  46953. set: function (value) {
  46954. this._refreshRate = value;
  46955. this.resetRefreshCounter();
  46956. },
  46957. enumerable: true,
  46958. configurable: true
  46959. });
  46960. ProceduralTexture.prototype._shouldRender = function () {
  46961. if (!this.isEnabled || !this.isReady() || !this._texture) {
  46962. return false;
  46963. }
  46964. if (this._fallbackTextureUsed) {
  46965. return false;
  46966. }
  46967. if (this._currentRefreshId === -1) {
  46968. this._currentRefreshId = 1;
  46969. return true;
  46970. }
  46971. if (this.refreshRate === this._currentRefreshId) {
  46972. this._currentRefreshId = 1;
  46973. return true;
  46974. }
  46975. this._currentRefreshId++;
  46976. return false;
  46977. };
  46978. ProceduralTexture.prototype.getRenderSize = function () {
  46979. return this._size;
  46980. };
  46981. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  46982. if (this._fallbackTextureUsed) {
  46983. return;
  46984. }
  46985. this.releaseInternalTexture();
  46986. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  46987. };
  46988. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  46989. if (this._uniforms.indexOf(uniformName) === -1) {
  46990. this._uniforms.push(uniformName);
  46991. }
  46992. };
  46993. ProceduralTexture.prototype.setTexture = function (name, texture) {
  46994. if (this._samplers.indexOf(name) === -1) {
  46995. this._samplers.push(name);
  46996. }
  46997. this._textures[name] = texture;
  46998. return this;
  46999. };
  47000. ProceduralTexture.prototype.setFloat = function (name, value) {
  47001. this._checkUniform(name);
  47002. this._floats[name] = value;
  47003. return this;
  47004. };
  47005. ProceduralTexture.prototype.setFloats = function (name, value) {
  47006. this._checkUniform(name);
  47007. this._floatsArrays[name] = value;
  47008. return this;
  47009. };
  47010. ProceduralTexture.prototype.setColor3 = function (name, value) {
  47011. this._checkUniform(name);
  47012. this._colors3[name] = value;
  47013. return this;
  47014. };
  47015. ProceduralTexture.prototype.setColor4 = function (name, value) {
  47016. this._checkUniform(name);
  47017. this._colors4[name] = value;
  47018. return this;
  47019. };
  47020. ProceduralTexture.prototype.setVector2 = function (name, value) {
  47021. this._checkUniform(name);
  47022. this._vectors2[name] = value;
  47023. return this;
  47024. };
  47025. ProceduralTexture.prototype.setVector3 = function (name, value) {
  47026. this._checkUniform(name);
  47027. this._vectors3[name] = value;
  47028. return this;
  47029. };
  47030. ProceduralTexture.prototype.setMatrix = function (name, value) {
  47031. this._checkUniform(name);
  47032. this._matrices[name] = value;
  47033. return this;
  47034. };
  47035. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47036. var scene = this.getScene();
  47037. var engine = scene.getEngine();
  47038. // Render
  47039. engine.enableEffect(this._effect);
  47040. engine.setState(false);
  47041. // Texture
  47042. for (var name in this._textures) {
  47043. this._effect.setTexture(name, this._textures[name]);
  47044. }
  47045. // Float
  47046. for (name in this._floats) {
  47047. this._effect.setFloat(name, this._floats[name]);
  47048. }
  47049. // Floats
  47050. for (name in this._floatsArrays) {
  47051. this._effect.setArray(name, this._floatsArrays[name]);
  47052. }
  47053. // Color3
  47054. for (name in this._colors3) {
  47055. this._effect.setColor3(name, this._colors3[name]);
  47056. }
  47057. // Color4
  47058. for (name in this._colors4) {
  47059. var color = this._colors4[name];
  47060. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47061. }
  47062. // Vector2
  47063. for (name in this._vectors2) {
  47064. this._effect.setVector2(name, this._vectors2[name]);
  47065. }
  47066. // Vector3
  47067. for (name in this._vectors3) {
  47068. this._effect.setVector3(name, this._vectors3[name]);
  47069. }
  47070. // Matrix
  47071. for (name in this._matrices) {
  47072. this._effect.setMatrix(name, this._matrices[name]);
  47073. }
  47074. if (this.isCube) {
  47075. for (var face = 0; face < 6; face++) {
  47076. engine.bindFramebuffer(this._texture, face);
  47077. // VBOs
  47078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47079. this._effect.setFloat("face", face);
  47080. // Clear
  47081. engine.clear(scene.clearColor, true, true, true);
  47082. // Draw order
  47083. engine.draw(true, 0, 6);
  47084. // Mipmaps
  47085. if (face === 5) {
  47086. engine.generateMipMapsForCubemap(this._texture);
  47087. }
  47088. }
  47089. }
  47090. else {
  47091. engine.bindFramebuffer(this._texture);
  47092. // VBOs
  47093. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  47094. // Clear
  47095. engine.clear(scene.clearColor, true, true, true);
  47096. // Draw order
  47097. engine.draw(true, 0, 6);
  47098. }
  47099. // Unbind
  47100. engine.unBindFramebuffer(this._texture, this.isCube);
  47101. if (this.onGenerated) {
  47102. this.onGenerated();
  47103. }
  47104. };
  47105. ProceduralTexture.prototype.clone = function () {
  47106. var textureSize = this.getSize();
  47107. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  47108. // Base texture
  47109. newTexture.hasAlpha = this.hasAlpha;
  47110. newTexture.level = this.level;
  47111. // RenderTarget Texture
  47112. newTexture.coordinatesMode = this.coordinatesMode;
  47113. return newTexture;
  47114. };
  47115. ProceduralTexture.prototype.dispose = function () {
  47116. var index = this.getScene()._proceduralTextures.indexOf(this);
  47117. if (index >= 0) {
  47118. this.getScene()._proceduralTextures.splice(index, 1);
  47119. }
  47120. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47121. if (vertexBuffer) {
  47122. vertexBuffer.dispose();
  47123. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47124. }
  47125. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  47126. this._indexBuffer = null;
  47127. }
  47128. _super.prototype.dispose.call(this);
  47129. };
  47130. return ProceduralTexture;
  47131. }(BABYLON.Texture));
  47132. BABYLON.ProceduralTexture = ProceduralTexture;
  47133. })(BABYLON || (BABYLON = {}));
  47134. //# sourceMappingURL=babylon.proceduralTexture.js.map
  47135. /// <reference path="babylon.proceduralTexture.ts" />
  47136. var BABYLON;
  47137. (function (BABYLON) {
  47138. var CustomProceduralTexture = (function (_super) {
  47139. __extends(CustomProceduralTexture, _super);
  47140. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  47141. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  47142. _this._animate = true;
  47143. _this._time = 0;
  47144. _this._texturePath = texturePath;
  47145. //Try to load json
  47146. _this.loadJson(texturePath);
  47147. _this.refreshRate = 1;
  47148. return _this;
  47149. }
  47150. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  47151. var _this = this;
  47152. var that = this;
  47153. function noConfigFile() {
  47154. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  47155. try {
  47156. that.setFragment(that._texturePath);
  47157. }
  47158. catch (ex) {
  47159. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  47160. }
  47161. }
  47162. var configFileUrl = jsonUrl + "/config.json";
  47163. var xhr = new XMLHttpRequest();
  47164. xhr.open("GET", configFileUrl, true);
  47165. xhr.addEventListener("load", function () {
  47166. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  47167. try {
  47168. _this._config = JSON.parse(xhr.response);
  47169. _this.updateShaderUniforms();
  47170. _this.updateTextures();
  47171. _this.setFragment(_this._texturePath + "/custom");
  47172. _this._animate = _this._config.animate;
  47173. _this.refreshRate = _this._config.refreshrate;
  47174. }
  47175. catch (ex) {
  47176. noConfigFile();
  47177. }
  47178. }
  47179. else {
  47180. noConfigFile();
  47181. }
  47182. }, false);
  47183. xhr.addEventListener("error", function () {
  47184. noConfigFile();
  47185. }, false);
  47186. try {
  47187. xhr.send();
  47188. }
  47189. catch (ex) {
  47190. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  47191. }
  47192. };
  47193. CustomProceduralTexture.prototype.isReady = function () {
  47194. if (!_super.prototype.isReady.call(this)) {
  47195. return false;
  47196. }
  47197. for (var name in this._textures) {
  47198. var texture = this._textures[name];
  47199. if (!texture.isReady()) {
  47200. return false;
  47201. }
  47202. }
  47203. return true;
  47204. };
  47205. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  47206. if (this._animate) {
  47207. this._time += this.getScene().getAnimationRatio() * 0.03;
  47208. this.updateShaderUniforms();
  47209. }
  47210. _super.prototype.render.call(this, useCameraPostProcess);
  47211. };
  47212. CustomProceduralTexture.prototype.updateTextures = function () {
  47213. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  47214. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  47215. }
  47216. };
  47217. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  47218. if (this._config) {
  47219. for (var j = 0; j < this._config.uniforms.length; j++) {
  47220. var uniform = this._config.uniforms[j];
  47221. switch (uniform.type) {
  47222. case "float":
  47223. this.setFloat(uniform.name, uniform.value);
  47224. break;
  47225. case "color3":
  47226. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  47227. break;
  47228. case "color4":
  47229. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  47230. break;
  47231. case "vector2":
  47232. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  47233. break;
  47234. case "vector3":
  47235. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  47236. break;
  47237. }
  47238. }
  47239. }
  47240. this.setFloat("time", this._time);
  47241. };
  47242. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  47243. get: function () {
  47244. return this._animate;
  47245. },
  47246. set: function (value) {
  47247. this._animate = value;
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. return CustomProceduralTexture;
  47253. }(BABYLON.ProceduralTexture));
  47254. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  47255. })(BABYLON || (BABYLON = {}));
  47256. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  47257. var BABYLON;
  47258. (function (BABYLON) {
  47259. var FreeCameraGamepadInput = (function () {
  47260. function FreeCameraGamepadInput() {
  47261. this.gamepadAngularSensibility = 200;
  47262. this.gamepadMoveSensibility = 40;
  47263. // private members
  47264. this._cameraTransform = BABYLON.Matrix.Identity();
  47265. this._deltaTransform = BABYLON.Vector3.Zero();
  47266. this._vector3 = BABYLON.Vector3.Zero();
  47267. this._vector2 = BABYLON.Vector2.Zero();
  47268. }
  47269. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47270. var _this = this;
  47271. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47272. };
  47273. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  47274. if (this._gamepads) {
  47275. this._gamepads.dispose();
  47276. }
  47277. this.gamepad = null;
  47278. };
  47279. FreeCameraGamepadInput.prototype.checkInputs = function () {
  47280. if (this.gamepad && this.gamepad.leftStick) {
  47281. var camera = this.camera;
  47282. var LSValues = this.gamepad.leftStick;
  47283. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  47284. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47285. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  47286. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  47287. var RSValues = this.gamepad.rightStick;
  47288. if (RSValues) {
  47289. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  47290. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  47291. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  47292. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  47293. }
  47294. else {
  47295. RSValues = { x: 0, y: 0 };
  47296. }
  47297. if (!camera.rotationQuaternion) {
  47298. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  47299. }
  47300. else {
  47301. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  47302. }
  47303. var speed = camera._computeLocalCameraSpeed() * 50.0;
  47304. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  47305. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  47306. camera.cameraDirection.addInPlace(this._deltaTransform);
  47307. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  47308. camera.cameraRotation.addInPlace(this._vector2);
  47309. }
  47310. };
  47311. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47312. // Only the first gamepad found can control the camera
  47313. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47314. // prioritize XBOX gamepads.
  47315. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47316. this.gamepad = gamepad;
  47317. }
  47318. }
  47319. };
  47320. FreeCameraGamepadInput.prototype.getTypeName = function () {
  47321. return "FreeCameraGamepadInput";
  47322. };
  47323. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  47324. return "gamepad";
  47325. };
  47326. return FreeCameraGamepadInput;
  47327. }());
  47328. __decorate([
  47329. BABYLON.serialize()
  47330. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  47331. __decorate([
  47332. BABYLON.serialize()
  47333. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47334. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  47335. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  47336. })(BABYLON || (BABYLON = {}));
  47337. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  47338. var BABYLON;
  47339. (function (BABYLON) {
  47340. var ArcRotateCameraGamepadInput = (function () {
  47341. function ArcRotateCameraGamepadInput() {
  47342. this.gamepadRotationSensibility = 80;
  47343. this.gamepadMoveSensibility = 40;
  47344. }
  47345. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  47346. var _this = this;
  47347. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  47348. };
  47349. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  47350. if (this._gamepads) {
  47351. this._gamepads.dispose();
  47352. }
  47353. this.gamepad = null;
  47354. };
  47355. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  47356. if (this.gamepad) {
  47357. var camera = this.camera;
  47358. var RSValues = this.gamepad.rightStick;
  47359. if (RSValues) {
  47360. if (RSValues.x != 0) {
  47361. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  47362. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  47363. camera.inertialAlphaOffset += normalizedRX;
  47364. }
  47365. }
  47366. if (RSValues.y != 0) {
  47367. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  47368. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  47369. camera.inertialBetaOffset += normalizedRY;
  47370. }
  47371. }
  47372. }
  47373. var LSValues = this.gamepad.leftStick;
  47374. if (LSValues && LSValues.y != 0) {
  47375. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  47376. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  47377. this.camera.inertialRadiusOffset -= normalizedLY;
  47378. }
  47379. }
  47380. }
  47381. };
  47382. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  47383. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  47384. // prioritize XBOX gamepads.
  47385. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  47386. this.gamepad = gamepad;
  47387. }
  47388. }
  47389. };
  47390. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  47391. return "ArcRotateCameraGamepadInput";
  47392. };
  47393. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  47394. return "gamepad";
  47395. };
  47396. return ArcRotateCameraGamepadInput;
  47397. }());
  47398. __decorate([
  47399. BABYLON.serialize()
  47400. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  47401. __decorate([
  47402. BABYLON.serialize()
  47403. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  47404. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  47405. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  47406. })(BABYLON || (BABYLON = {}));
  47407. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  47408. var BABYLON;
  47409. (function (BABYLON) {
  47410. var Gamepads = (function () {
  47411. function Gamepads(ongamedpadconnected, ongamedpaddisconnected) {
  47412. var _this = this;
  47413. this.babylonGamepads = [];
  47414. this.oneGamepadConnected = false;
  47415. this.isMonitoring = false;
  47416. this.gamepadEventSupported = 'GamepadEvent' in window;
  47417. this.gamepadSupport = (navigator.getGamepads ||
  47418. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  47419. this._callbackGamepadConnected = ongamedpadconnected;
  47420. this._callbackGamepadDisconnected = ongamedpaddisconnected;
  47421. if (this.gamepadSupport) {
  47422. //first add already-connected gamepads
  47423. this._updateGamepadObjects();
  47424. if (this.babylonGamepads.length) {
  47425. this._startMonitoringGamepads();
  47426. }
  47427. // Checking if the gamepad connected event is supported (like in Firefox)
  47428. if (this.gamepadEventSupported) {
  47429. this._onGamepadConnectedEvent = function (evt) {
  47430. _this._onGamepadConnected(evt.gamepad);
  47431. };
  47432. this._onGamepadDisonnectedEvent = function (evt) {
  47433. _this._onGamepadDisconnected(evt.gamepad);
  47434. };
  47435. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47436. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47437. }
  47438. else {
  47439. this._startMonitoringGamepads();
  47440. }
  47441. }
  47442. }
  47443. Gamepads.prototype.dispose = function () {
  47444. if (this._onGamepadConnectedEvent) {
  47445. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47446. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47447. this._onGamepadConnectedEvent = null;
  47448. this._onGamepadDisonnectedEvent = null;
  47449. }
  47450. this.oneGamepadConnected = false;
  47451. this._stopMonitoringGamepads();
  47452. this.babylonGamepads = [];
  47453. };
  47454. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  47455. // Protection code for Chrome which has a very buggy gamepad implementation...
  47456. // And raises a connected event on disconnection for instance
  47457. if (gamepad.index in this.babylonGamepads) {
  47458. return;
  47459. }
  47460. var newGamepad = this._addNewGamepad(gamepad);
  47461. if (this._callbackGamepadConnected)
  47462. this._callbackGamepadConnected(newGamepad);
  47463. this._startMonitoringGamepads();
  47464. };
  47465. Gamepads.prototype._addNewGamepad = function (gamepad) {
  47466. if (!this.oneGamepadConnected) {
  47467. this.oneGamepadConnected = true;
  47468. }
  47469. var newGamepad;
  47470. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  47471. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  47472. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  47473. }
  47474. else if (gamepad.pose) {
  47475. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  47476. }
  47477. else {
  47478. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  47479. }
  47480. this.babylonGamepads.push(newGamepad);
  47481. return newGamepad;
  47482. };
  47483. Gamepads.prototype._onGamepadDisconnected = function (gamepad) {
  47484. // Remove the gamepad from the list of gamepads to monitor.
  47485. for (var i in this.babylonGamepads) {
  47486. if (this.babylonGamepads[i].index == gamepad.index) {
  47487. this.babylonGamepads.splice(+i, 1);
  47488. break;
  47489. }
  47490. }
  47491. // If no gamepads are left, stop the polling loop.
  47492. if (this.babylonGamepads.length == 0) {
  47493. this._stopMonitoringGamepads();
  47494. this.oneGamepadConnected = false;
  47495. }
  47496. if (this._callbackGamepadDisconnected)
  47497. this._callbackGamepadDisconnected(gamepad);
  47498. };
  47499. Gamepads.prototype._startMonitoringGamepads = function () {
  47500. if (!this.isMonitoring) {
  47501. this.isMonitoring = true;
  47502. this._checkGamepadsStatus();
  47503. }
  47504. };
  47505. Gamepads.prototype._stopMonitoringGamepads = function () {
  47506. this.isMonitoring = false;
  47507. };
  47508. Gamepads.prototype._checkGamepadsStatus = function () {
  47509. var _this = this;
  47510. // Hack to be compatible Chrome
  47511. this._updateGamepadObjects();
  47512. for (var i in this.babylonGamepads) {
  47513. this.babylonGamepads[i].update();
  47514. }
  47515. if (this.isMonitoring) {
  47516. if (window.requestAnimationFrame) {
  47517. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47518. }
  47519. else if (window.mozRequestAnimationFrame) {
  47520. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47521. }
  47522. else if (window.webkitRequestAnimationFrame) {
  47523. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47524. }
  47525. }
  47526. };
  47527. // This function is called only on Chrome, which does not properly support
  47528. // connection/disconnection events and forces you to recopy again the gamepad object
  47529. Gamepads.prototype._updateGamepadObjects = function () {
  47530. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47531. for (var i = 0; i < gamepads.length; i++) {
  47532. if (gamepads[i]) {
  47533. if (!(gamepads[i].index in this.babylonGamepads)) {
  47534. var newGamepad = this._addNewGamepad(gamepads[i]);
  47535. if (this._callbackGamepadConnected) {
  47536. this._callbackGamepadConnected(newGamepad);
  47537. }
  47538. }
  47539. else {
  47540. // Forced to copy again this object for Chrome for unknown reason
  47541. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47542. }
  47543. }
  47544. }
  47545. };
  47546. return Gamepads;
  47547. }());
  47548. BABYLON.Gamepads = Gamepads;
  47549. var StickValues = (function () {
  47550. function StickValues(x, y) {
  47551. this.x = x;
  47552. this.y = y;
  47553. }
  47554. return StickValues;
  47555. }());
  47556. BABYLON.StickValues = StickValues;
  47557. var Gamepad = (function () {
  47558. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47559. if (leftStickX === void 0) { leftStickX = 0; }
  47560. if (leftStickY === void 0) { leftStickY = 1; }
  47561. if (rightStickX === void 0) { rightStickX = 2; }
  47562. if (rightStickY === void 0) { rightStickY = 3; }
  47563. this.id = id;
  47564. this.index = index;
  47565. this.browserGamepad = browserGamepad;
  47566. this.type = Gamepad.GAMEPAD;
  47567. this._leftStickAxisX = leftStickX;
  47568. this._leftStickAxisY = leftStickY;
  47569. this._rightStickAxisX = rightStickX;
  47570. this._rightStickAxisY = rightStickY;
  47571. if (this.browserGamepad.axes.length >= 2) {
  47572. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47573. }
  47574. if (this.browserGamepad.axes.length >= 4) {
  47575. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47576. }
  47577. }
  47578. Gamepad.prototype.onleftstickchanged = function (callback) {
  47579. this._onleftstickchanged = callback;
  47580. };
  47581. Gamepad.prototype.onrightstickchanged = function (callback) {
  47582. this._onrightstickchanged = callback;
  47583. };
  47584. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47585. get: function () {
  47586. return this._leftStick;
  47587. },
  47588. set: function (newValues) {
  47589. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47590. this._onleftstickchanged(newValues);
  47591. }
  47592. this._leftStick = newValues;
  47593. },
  47594. enumerable: true,
  47595. configurable: true
  47596. });
  47597. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47598. get: function () {
  47599. return this._rightStick;
  47600. },
  47601. set: function (newValues) {
  47602. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47603. this._onrightstickchanged(newValues);
  47604. }
  47605. this._rightStick = newValues;
  47606. },
  47607. enumerable: true,
  47608. configurable: true
  47609. });
  47610. Gamepad.prototype.update = function () {
  47611. if (this._leftStick) {
  47612. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47613. }
  47614. if (this._rightStick) {
  47615. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47616. }
  47617. };
  47618. return Gamepad;
  47619. }());
  47620. Gamepad.GAMEPAD = 0;
  47621. Gamepad.GENERIC = 1;
  47622. Gamepad.XBOX = 2;
  47623. Gamepad.POSE_ENABLED = 3;
  47624. BABYLON.Gamepad = Gamepad;
  47625. var GenericPad = (function (_super) {
  47626. __extends(GenericPad, _super);
  47627. function GenericPad(id, index, browserGamepad) {
  47628. var _this = _super.call(this, id, index, browserGamepad) || this;
  47629. _this.type = Gamepad.GENERIC;
  47630. _this._buttons = new Array(browserGamepad.buttons.length);
  47631. return _this;
  47632. }
  47633. GenericPad.prototype.onbuttondown = function (callback) {
  47634. this._onbuttondown = callback;
  47635. };
  47636. GenericPad.prototype.onbuttonup = function (callback) {
  47637. this._onbuttonup = callback;
  47638. };
  47639. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47640. if (newValue !== currentValue) {
  47641. if (this._onbuttondown && newValue === 1) {
  47642. this._onbuttondown(buttonIndex);
  47643. }
  47644. if (this._onbuttonup && newValue === 0) {
  47645. this._onbuttonup(buttonIndex);
  47646. }
  47647. }
  47648. return newValue;
  47649. };
  47650. GenericPad.prototype.update = function () {
  47651. _super.prototype.update.call(this);
  47652. for (var index = 0; index < this._buttons.length; index++) {
  47653. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  47654. }
  47655. };
  47656. return GenericPad;
  47657. }(Gamepad));
  47658. BABYLON.GenericPad = GenericPad;
  47659. var Xbox360Button;
  47660. (function (Xbox360Button) {
  47661. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47662. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47663. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47664. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47665. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47666. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47667. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47668. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47669. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47670. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47671. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47672. var Xbox360Dpad;
  47673. (function (Xbox360Dpad) {
  47674. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47675. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47676. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47677. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47678. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47679. var Xbox360Pad = (function (_super) {
  47680. __extends(Xbox360Pad, _super);
  47681. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47682. if (xboxOne === void 0) { xboxOne = false; }
  47683. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47684. _this._leftTrigger = 0;
  47685. _this._rightTrigger = 0;
  47686. _this._buttonA = 0;
  47687. _this._buttonB = 0;
  47688. _this._buttonX = 0;
  47689. _this._buttonY = 0;
  47690. _this._buttonBack = 0;
  47691. _this._buttonStart = 0;
  47692. _this._buttonLB = 0;
  47693. _this._buttonRB = 0;
  47694. _this._buttonLeftStick = 0;
  47695. _this._buttonRightStick = 0;
  47696. _this._dPadUp = 0;
  47697. _this._dPadDown = 0;
  47698. _this._dPadLeft = 0;
  47699. _this._dPadRight = 0;
  47700. _this._isXboxOnePad = false;
  47701. _this.type = Gamepad.XBOX;
  47702. _this._isXboxOnePad = xboxOne;
  47703. return _this;
  47704. }
  47705. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47706. this._onlefttriggerchanged = callback;
  47707. };
  47708. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47709. this._onrighttriggerchanged = callback;
  47710. };
  47711. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47712. get: function () {
  47713. return this._leftTrigger;
  47714. },
  47715. set: function (newValue) {
  47716. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47717. this._onlefttriggerchanged(newValue);
  47718. }
  47719. this._leftTrigger = newValue;
  47720. },
  47721. enumerable: true,
  47722. configurable: true
  47723. });
  47724. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47725. get: function () {
  47726. return this._rightTrigger;
  47727. },
  47728. set: function (newValue) {
  47729. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47730. this._onrighttriggerchanged(newValue);
  47731. }
  47732. this._rightTrigger = newValue;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47738. this._onbuttondown = callback;
  47739. };
  47740. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47741. this._onbuttonup = callback;
  47742. };
  47743. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47744. this._ondpaddown = callback;
  47745. };
  47746. Xbox360Pad.prototype.ondpadup = function (callback) {
  47747. this._ondpadup = callback;
  47748. };
  47749. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47750. if (newValue !== currentValue) {
  47751. if (this._onbuttondown && newValue === 1) {
  47752. this._onbuttondown(buttonType);
  47753. }
  47754. if (this._onbuttonup && newValue === 0) {
  47755. this._onbuttonup(buttonType);
  47756. }
  47757. }
  47758. return newValue;
  47759. };
  47760. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47761. if (newValue !== currentValue) {
  47762. if (this._ondpaddown && newValue === 1) {
  47763. this._ondpaddown(buttonType);
  47764. }
  47765. if (this._ondpadup && newValue === 0) {
  47766. this._ondpadup(buttonType);
  47767. }
  47768. }
  47769. return newValue;
  47770. };
  47771. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47772. get: function () {
  47773. return this._buttonA;
  47774. },
  47775. set: function (value) {
  47776. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47782. get: function () {
  47783. return this._buttonB;
  47784. },
  47785. set: function (value) {
  47786. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47787. },
  47788. enumerable: true,
  47789. configurable: true
  47790. });
  47791. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47792. get: function () {
  47793. return this._buttonX;
  47794. },
  47795. set: function (value) {
  47796. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47797. },
  47798. enumerable: true,
  47799. configurable: true
  47800. });
  47801. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47802. get: function () {
  47803. return this._buttonY;
  47804. },
  47805. set: function (value) {
  47806. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47807. },
  47808. enumerable: true,
  47809. configurable: true
  47810. });
  47811. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47812. get: function () {
  47813. return this._buttonStart;
  47814. },
  47815. set: function (value) {
  47816. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47817. },
  47818. enumerable: true,
  47819. configurable: true
  47820. });
  47821. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47822. get: function () {
  47823. return this._buttonBack;
  47824. },
  47825. set: function (value) {
  47826. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47827. },
  47828. enumerable: true,
  47829. configurable: true
  47830. });
  47831. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47832. get: function () {
  47833. return this._buttonLB;
  47834. },
  47835. set: function (value) {
  47836. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47837. },
  47838. enumerable: true,
  47839. configurable: true
  47840. });
  47841. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47842. get: function () {
  47843. return this._buttonRB;
  47844. },
  47845. set: function (value) {
  47846. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47847. },
  47848. enumerable: true,
  47849. configurable: true
  47850. });
  47851. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47852. get: function () {
  47853. return this._buttonLeftStick;
  47854. },
  47855. set: function (value) {
  47856. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47857. },
  47858. enumerable: true,
  47859. configurable: true
  47860. });
  47861. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47862. get: function () {
  47863. return this._buttonRightStick;
  47864. },
  47865. set: function (value) {
  47866. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47867. },
  47868. enumerable: true,
  47869. configurable: true
  47870. });
  47871. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47872. get: function () {
  47873. return this._dPadUp;
  47874. },
  47875. set: function (value) {
  47876. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47877. },
  47878. enumerable: true,
  47879. configurable: true
  47880. });
  47881. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47882. get: function () {
  47883. return this._dPadDown;
  47884. },
  47885. set: function (value) {
  47886. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47887. },
  47888. enumerable: true,
  47889. configurable: true
  47890. });
  47891. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47892. get: function () {
  47893. return this._dPadLeft;
  47894. },
  47895. set: function (value) {
  47896. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47897. },
  47898. enumerable: true,
  47899. configurable: true
  47900. });
  47901. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47902. get: function () {
  47903. return this._dPadRight;
  47904. },
  47905. set: function (value) {
  47906. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47907. },
  47908. enumerable: true,
  47909. configurable: true
  47910. });
  47911. Xbox360Pad.prototype.update = function () {
  47912. _super.prototype.update.call(this);
  47913. if (this._isXboxOnePad) {
  47914. this.buttonA = this.browserGamepad.buttons[0].value;
  47915. this.buttonB = this.browserGamepad.buttons[1].value;
  47916. this.buttonX = this.browserGamepad.buttons[2].value;
  47917. this.buttonY = this.browserGamepad.buttons[3].value;
  47918. this.buttonLB = this.browserGamepad.buttons[4].value;
  47919. this.buttonRB = this.browserGamepad.buttons[5].value;
  47920. this.leftTrigger = this.browserGamepad.axes[2];
  47921. this.rightTrigger = this.browserGamepad.axes[5];
  47922. this.buttonBack = this.browserGamepad.buttons[9].value;
  47923. this.buttonStart = this.browserGamepad.buttons[8].value;
  47924. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47925. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47926. this.dPadUp = this.browserGamepad.buttons[11].value;
  47927. this.dPadDown = this.browserGamepad.buttons[12].value;
  47928. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47929. this.dPadRight = this.browserGamepad.buttons[14].value;
  47930. }
  47931. else {
  47932. this.buttonA = this.browserGamepad.buttons[0].value;
  47933. this.buttonB = this.browserGamepad.buttons[1].value;
  47934. this.buttonX = this.browserGamepad.buttons[2].value;
  47935. this.buttonY = this.browserGamepad.buttons[3].value;
  47936. this.buttonLB = this.browserGamepad.buttons[4].value;
  47937. this.buttonRB = this.browserGamepad.buttons[5].value;
  47938. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47939. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47940. this.buttonBack = this.browserGamepad.buttons[8].value;
  47941. this.buttonStart = this.browserGamepad.buttons[9].value;
  47942. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47943. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47944. this.dPadUp = this.browserGamepad.buttons[12].value;
  47945. this.dPadDown = this.browserGamepad.buttons[13].value;
  47946. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47947. this.dPadRight = this.browserGamepad.buttons[15].value;
  47948. }
  47949. };
  47950. return Xbox360Pad;
  47951. }(Gamepad));
  47952. BABYLON.Xbox360Pad = Xbox360Pad;
  47953. })(BABYLON || (BABYLON = {}));
  47954. //# sourceMappingURL=babylon.gamepads.js.map
  47955. var BABYLON;
  47956. (function (BABYLON) {
  47957. var PoseEnabledControllerType;
  47958. (function (PoseEnabledControllerType) {
  47959. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  47960. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  47961. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  47962. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  47963. var PoseEnabledControllerHelper = (function () {
  47964. function PoseEnabledControllerHelper() {
  47965. }
  47966. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  47967. // for now, only Oculus and Vive are supported
  47968. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  47969. return new OculusTouchController(vrGamepad);
  47970. }
  47971. else {
  47972. return new ViveController(vrGamepad);
  47973. }
  47974. };
  47975. return PoseEnabledControllerHelper;
  47976. }());
  47977. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  47978. var PoseEnabledController = (function (_super) {
  47979. __extends(PoseEnabledController, _super);
  47980. function PoseEnabledController(vrGamepad) {
  47981. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  47982. _this.vrGamepad = vrGamepad;
  47983. _this.deviceScaleFactor = 1;
  47984. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  47985. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  47986. _this.controllerType = PoseEnabledControllerType.GENERIC;
  47987. _this.position = BABYLON.Vector3.Zero();
  47988. _this.rotationQuaternion = new BABYLON.Quaternion();
  47989. _this.devicePosition = BABYLON.Vector3.Zero();
  47990. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  47991. _this._calculatedPosition = BABYLON.Vector3.Zero();
  47992. _this._calculatedRotation = new BABYLON.Quaternion();
  47993. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  47994. return _this;
  47995. }
  47996. PoseEnabledController.prototype.update = function () {
  47997. _super.prototype.update.call(this);
  47998. var pose = this.vrGamepad.pose;
  47999. this.updateFromDevice(pose);
  48000. if (this._mesh) {
  48001. this._mesh.position.copyFrom(this._calculatedPosition);
  48002. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  48003. }
  48004. };
  48005. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  48006. if (poseData) {
  48007. this.rawPose = poseData;
  48008. if (poseData.position) {
  48009. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  48010. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  48011. this.devicePosition.z *= -1;
  48012. }
  48013. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  48014. this._calculatedPosition.addInPlace(this.position);
  48015. }
  48016. if (poseData.orientation) {
  48017. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  48018. if (this._mesh) {
  48019. if (this._mesh.getScene().useRightHandedSystem) {
  48020. this.deviceRotationQuaternion.z *= -1;
  48021. this.deviceRotationQuaternion.w *= -1;
  48022. }
  48023. else {
  48024. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  48025. }
  48026. }
  48027. // if the camera is set, rotate to the camera's rotation
  48028. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  48029. }
  48030. }
  48031. };
  48032. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  48033. if (this._mesh) {
  48034. this._mesh.parent = undefined;
  48035. }
  48036. this._mesh = mesh;
  48037. if (this._poseControlledCamera) {
  48038. this._mesh.parent = this._poseControlledCamera;
  48039. }
  48040. if (!this._mesh.rotationQuaternion) {
  48041. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  48042. }
  48043. };
  48044. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  48045. this._poseControlledCamera = camera;
  48046. if (this._mesh) {
  48047. this._mesh.parent = this._poseControlledCamera;
  48048. }
  48049. };
  48050. PoseEnabledController.prototype.detachMesh = function () {
  48051. this._mesh = undefined;
  48052. };
  48053. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  48054. get: function () {
  48055. return this._mesh;
  48056. },
  48057. enumerable: true,
  48058. configurable: true
  48059. });
  48060. PoseEnabledController.prototype.getForwardRay = function (length) {
  48061. if (length === void 0) { length = 100; }
  48062. if (!this.mesh) {
  48063. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  48064. }
  48065. var m = this.mesh.getWorldMatrix();
  48066. var origin = m.getTranslation();
  48067. var forward = new BABYLON.Vector3(0, 0, -1);
  48068. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  48069. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  48070. return new BABYLON.Ray(origin, direction, length);
  48071. };
  48072. return PoseEnabledController;
  48073. }(BABYLON.Gamepad));
  48074. BABYLON.PoseEnabledController = PoseEnabledController;
  48075. var WebVRController = (function (_super) {
  48076. __extends(WebVRController, _super);
  48077. function WebVRController(vrGamepad) {
  48078. var _this = _super.call(this, vrGamepad) || this;
  48079. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  48080. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  48081. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  48082. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  48083. _this.onPadStateChangedObservable = new BABYLON.Observable();
  48084. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  48085. _this.pad = { x: 0, y: 0 };
  48086. // avoid GC, store state in a tmp object
  48087. _this._changes = {
  48088. pressChanged: false,
  48089. touchChanged: false,
  48090. valueChanged: false,
  48091. changed: false
  48092. };
  48093. _this._buttons = new Array(vrGamepad.buttons.length);
  48094. _this.hand = vrGamepad.hand;
  48095. return _this;
  48096. }
  48097. WebVRController.prototype.onButtonStateChange = function (callback) {
  48098. this._onButtonStateChange = callback;
  48099. };
  48100. WebVRController.prototype.update = function () {
  48101. _super.prototype.update.call(this);
  48102. for (var index = 0; index < this._buttons.length; index++) {
  48103. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  48104. }
  48105. ;
  48106. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  48107. this.pad.x = this.leftStick.x;
  48108. this.pad.y = this.leftStick.y;
  48109. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  48110. }
  48111. };
  48112. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  48113. if (!currentState) {
  48114. this._buttons[buttonIndex] = {
  48115. pressed: newState.pressed,
  48116. touched: newState.touched,
  48117. value: newState.value
  48118. };
  48119. return;
  48120. }
  48121. this._checkChanges(newState, currentState);
  48122. if (this._changes.changed) {
  48123. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  48124. this.handleButtonChange(buttonIndex, newState, this._changes);
  48125. }
  48126. this._buttons[buttonIndex].pressed = newState.pressed;
  48127. this._buttons[buttonIndex].touched = newState.touched;
  48128. // oculus triggers are never 0, thou not touched.
  48129. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  48130. };
  48131. WebVRController.prototype._checkChanges = function (newState, currentState) {
  48132. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  48133. this._changes.touchChanged = newState.touched !== currentState.touched;
  48134. this._changes.valueChanged = newState.value !== currentState.value;
  48135. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  48136. return this._changes;
  48137. };
  48138. return WebVRController;
  48139. }(PoseEnabledController));
  48140. BABYLON.WebVRController = WebVRController;
  48141. var OculusTouchController = (function (_super) {
  48142. __extends(OculusTouchController, _super);
  48143. function OculusTouchController(vrGamepad) {
  48144. var _this = _super.call(this, vrGamepad) || this;
  48145. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  48146. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  48147. _this.controllerType = PoseEnabledControllerType.OCULUS;
  48148. return _this;
  48149. }
  48150. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48151. var _this = this;
  48152. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  48153. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  48154. /*
  48155. Parent Mesh name: oculus_touch_left
  48156. - body
  48157. - trigger
  48158. - thumbstick
  48159. - grip
  48160. - button_y
  48161. - button_x
  48162. - button_enter
  48163. */
  48164. _this._defaultModel = newMeshes[1];
  48165. if (meshLoaded) {
  48166. meshLoaded(_this._defaultModel);
  48167. }
  48168. _this.attachToMesh(_this._defaultModel);
  48169. });
  48170. };
  48171. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  48172. // helper getters for left and right hand.
  48173. get: function () {
  48174. if (this.hand === 'right') {
  48175. return this.onMainButtonStateChangedObservable;
  48176. }
  48177. else {
  48178. throw new Error('No A button on left hand');
  48179. }
  48180. },
  48181. enumerable: true,
  48182. configurable: true
  48183. });
  48184. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  48185. get: function () {
  48186. if (this.hand === 'right') {
  48187. return this.onSecondaryButtonStateChangedObservable;
  48188. }
  48189. else {
  48190. throw new Error('No B button on left hand');
  48191. }
  48192. },
  48193. enumerable: true,
  48194. configurable: true
  48195. });
  48196. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  48197. get: function () {
  48198. if (this.hand === 'left') {
  48199. return this.onMainButtonStateChangedObservable;
  48200. }
  48201. else {
  48202. throw new Error('No X button on right hand');
  48203. }
  48204. },
  48205. enumerable: true,
  48206. configurable: true
  48207. });
  48208. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  48209. get: function () {
  48210. if (this.hand === 'left') {
  48211. return this.onSecondaryButtonStateChangedObservable;
  48212. }
  48213. else {
  48214. throw new Error('No Y button on right hand');
  48215. }
  48216. },
  48217. enumerable: true,
  48218. configurable: true
  48219. });
  48220. /*
  48221. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  48222. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  48223. 2) secondary trigger (same)
  48224. 3) A (right) X (left), touch, pressed = value
  48225. 4) B / Y
  48226. 5) thumb rest
  48227. */
  48228. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48229. var notifyObject = state; //{ state: state, changes: changes };
  48230. var triggerDirection = this.hand === 'right' ? -1 : 1;
  48231. switch (buttonIdx) {
  48232. case 0:
  48233. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48234. return;
  48235. case 1:
  48236. if (this._defaultModel) {
  48237. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  48238. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  48239. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  48240. }
  48241. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48242. return;
  48243. case 2:
  48244. if (this._defaultModel) {
  48245. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  48246. }
  48247. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  48248. return;
  48249. case 3:
  48250. if (this._defaultModel) {
  48251. if (notifyObject.pressed) {
  48252. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  48253. }
  48254. else {
  48255. (this._defaultModel.getChildren()[1]).position.y = 0;
  48256. }
  48257. }
  48258. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48259. return;
  48260. case 4:
  48261. if (this._defaultModel) {
  48262. if (notifyObject.pressed) {
  48263. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48264. }
  48265. else {
  48266. (this._defaultModel.getChildren()[2]).position.y = 0;
  48267. }
  48268. }
  48269. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48270. return;
  48271. case 5:
  48272. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  48273. return;
  48274. }
  48275. };
  48276. return OculusTouchController;
  48277. }(WebVRController));
  48278. BABYLON.OculusTouchController = OculusTouchController;
  48279. var ViveController = (function (_super) {
  48280. __extends(ViveController, _super);
  48281. function ViveController(vrGamepad) {
  48282. var _this = _super.call(this, vrGamepad) || this;
  48283. _this.controllerType = PoseEnabledControllerType.VIVE;
  48284. return _this;
  48285. }
  48286. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  48287. var _this = this;
  48288. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  48289. /*
  48290. Parent Mesh name: ViveWand
  48291. - body
  48292. - r_gripper
  48293. - l_gripper
  48294. - menu_button
  48295. - system_button
  48296. - trackpad
  48297. - trigger
  48298. - LED
  48299. */
  48300. _this._defaultModel = newMeshes[1];
  48301. if (meshLoaded) {
  48302. meshLoaded(_this._defaultModel);
  48303. }
  48304. _this.attachToMesh(_this._defaultModel);
  48305. });
  48306. };
  48307. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  48308. get: function () {
  48309. return this.onMainButtonStateChangedObservable;
  48310. },
  48311. enumerable: true,
  48312. configurable: true
  48313. });
  48314. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  48315. get: function () {
  48316. return this.onMainButtonStateChangedObservable;
  48317. },
  48318. enumerable: true,
  48319. configurable: true
  48320. });
  48321. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  48322. get: function () {
  48323. return this.onSecondaryButtonStateChangedObservable;
  48324. },
  48325. enumerable: true,
  48326. configurable: true
  48327. });
  48328. /**
  48329. * Vive mapping:
  48330. * 0: touchpad
  48331. * 1: trigger
  48332. * 2: left AND right buttons
  48333. * 3: menu button
  48334. */
  48335. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  48336. var notifyObject = state; //{ state: state, changes: changes };
  48337. switch (buttonIdx) {
  48338. case 0:
  48339. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  48340. return;
  48341. case 1:
  48342. if (this._defaultModel) {
  48343. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  48344. }
  48345. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  48346. return;
  48347. case 2:
  48348. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  48349. return;
  48350. case 3:
  48351. if (this._defaultModel) {
  48352. if (notifyObject.pressed) {
  48353. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  48354. }
  48355. else {
  48356. (this._defaultModel.getChildren()[2]).position.y = 0;
  48357. }
  48358. }
  48359. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  48360. return;
  48361. }
  48362. };
  48363. return ViveController;
  48364. }(WebVRController));
  48365. BABYLON.ViveController = ViveController;
  48366. })(BABYLON || (BABYLON = {}));
  48367. //# sourceMappingURL=babylon.extendedGamepad.js.map
  48368. /// <reference path="babylon.targetCamera.ts" />
  48369. var BABYLON;
  48370. (function (BABYLON) {
  48371. var FollowCamera = (function (_super) {
  48372. __extends(FollowCamera, _super);
  48373. function FollowCamera(name, position, scene, lockedTarget) {
  48374. var _this = _super.call(this, name, position, scene) || this;
  48375. _this.radius = 12;
  48376. _this.rotationOffset = 0;
  48377. _this.heightOffset = 4;
  48378. _this.cameraAcceleration = 0.05;
  48379. _this.maxCameraSpeed = 20;
  48380. _this.lockedTarget = lockedTarget;
  48381. return _this;
  48382. }
  48383. FollowCamera.prototype.getRadians = function (degrees) {
  48384. return degrees * Math.PI / 180;
  48385. };
  48386. FollowCamera.prototype.follow = function (cameraTarget) {
  48387. if (!cameraTarget)
  48388. return;
  48389. var yRotation;
  48390. if (cameraTarget.rotationQuaternion) {
  48391. var rotMatrix = new BABYLON.Matrix();
  48392. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  48393. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  48394. }
  48395. else {
  48396. yRotation = cameraTarget.rotation.y;
  48397. }
  48398. var radians = this.getRadians(this.rotationOffset) + yRotation;
  48399. var targetPosition = cameraTarget.getAbsolutePosition();
  48400. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  48401. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  48402. var dx = targetX - this.position.x;
  48403. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  48404. var dz = (targetZ) - this.position.z;
  48405. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  48406. var vy = dy * this.cameraAcceleration;
  48407. var vz = dz * this.cameraAcceleration * 2;
  48408. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  48409. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48410. }
  48411. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  48412. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48413. }
  48414. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  48415. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  48416. }
  48417. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  48418. this.setTarget(targetPosition);
  48419. };
  48420. FollowCamera.prototype._checkInputs = function () {
  48421. _super.prototype._checkInputs.call(this);
  48422. this.follow(this.lockedTarget);
  48423. };
  48424. FollowCamera.prototype.getClassName = function () {
  48425. return "FollowCamera";
  48426. };
  48427. return FollowCamera;
  48428. }(BABYLON.TargetCamera));
  48429. __decorate([
  48430. BABYLON.serialize()
  48431. ], FollowCamera.prototype, "radius", void 0);
  48432. __decorate([
  48433. BABYLON.serialize()
  48434. ], FollowCamera.prototype, "rotationOffset", void 0);
  48435. __decorate([
  48436. BABYLON.serialize()
  48437. ], FollowCamera.prototype, "heightOffset", void 0);
  48438. __decorate([
  48439. BABYLON.serialize()
  48440. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  48441. __decorate([
  48442. BABYLON.serialize()
  48443. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  48444. __decorate([
  48445. BABYLON.serializeAsMeshReference("lockedTargetId")
  48446. ], FollowCamera.prototype, "lockedTarget", void 0);
  48447. BABYLON.FollowCamera = FollowCamera;
  48448. var ArcFollowCamera = (function (_super) {
  48449. __extends(ArcFollowCamera, _super);
  48450. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  48451. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48452. _this.alpha = alpha;
  48453. _this.beta = beta;
  48454. _this.radius = radius;
  48455. _this.target = target;
  48456. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  48457. _this.follow();
  48458. return _this;
  48459. }
  48460. ArcFollowCamera.prototype.follow = function () {
  48461. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  48462. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  48463. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  48464. var targetPosition = this.target.getAbsolutePosition();
  48465. this.position = targetPosition.add(this._cartesianCoordinates);
  48466. this.setTarget(targetPosition);
  48467. };
  48468. ArcFollowCamera.prototype._checkInputs = function () {
  48469. _super.prototype._checkInputs.call(this);
  48470. this.follow();
  48471. };
  48472. ArcFollowCamera.prototype.getClassName = function () {
  48473. return "ArcFollowCamera";
  48474. };
  48475. return ArcFollowCamera;
  48476. }(BABYLON.TargetCamera));
  48477. BABYLON.ArcFollowCamera = ArcFollowCamera;
  48478. })(BABYLON || (BABYLON = {}));
  48479. //# sourceMappingURL=babylon.followCamera.js.map
  48480. /// <reference path="babylon.touchCamera.ts" />
  48481. var BABYLON;
  48482. (function (BABYLON) {
  48483. // We're mainly based on the logic defined into the FreeCamera code
  48484. var UniversalCamera = (function (_super) {
  48485. __extends(UniversalCamera, _super);
  48486. //-- end properties for backward compatibility for inputs
  48487. function UniversalCamera(name, position, scene) {
  48488. var _this = _super.call(this, name, position, scene) || this;
  48489. _this.inputs.addGamepad();
  48490. return _this;
  48491. }
  48492. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  48493. //-- Begin properties for backward compatibility for inputs
  48494. get: function () {
  48495. var gamepad = this.inputs.attached["gamepad"];
  48496. if (gamepad)
  48497. return gamepad.gamepadAngularSensibility;
  48498. },
  48499. set: function (value) {
  48500. var gamepad = this.inputs.attached["gamepad"];
  48501. if (gamepad)
  48502. gamepad.gamepadAngularSensibility = value;
  48503. },
  48504. enumerable: true,
  48505. configurable: true
  48506. });
  48507. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  48508. get: function () {
  48509. var gamepad = this.inputs.attached["gamepad"];
  48510. if (gamepad)
  48511. return gamepad.gamepadMoveSensibility;
  48512. },
  48513. set: function (value) {
  48514. var gamepad = this.inputs.attached["gamepad"];
  48515. if (gamepad)
  48516. gamepad.gamepadMoveSensibility = value;
  48517. },
  48518. enumerable: true,
  48519. configurable: true
  48520. });
  48521. UniversalCamera.prototype.getClassName = function () {
  48522. return "UniversalCamera";
  48523. };
  48524. return UniversalCamera;
  48525. }(BABYLON.TouchCamera));
  48526. BABYLON.UniversalCamera = UniversalCamera;
  48527. })(BABYLON || (BABYLON = {}));
  48528. //# sourceMappingURL=babylon.universalCamera.js.map
  48529. /// <reference path="babylon.universalCamera.ts" />
  48530. var BABYLON;
  48531. (function (BABYLON) {
  48532. // We're mainly based on the logic defined into the FreeCamera code
  48533. var GamepadCamera = (function (_super) {
  48534. __extends(GamepadCamera, _super);
  48535. //-- end properties for backward compatibility for inputs
  48536. function GamepadCamera(name, position, scene) {
  48537. return _super.call(this, name, position, scene) || this;
  48538. }
  48539. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  48540. //-- Begin properties for backward compatibility for inputs
  48541. get: function () {
  48542. var gamepad = this.inputs.attached["gamepad"];
  48543. if (gamepad)
  48544. return gamepad.gamepadAngularSensibility;
  48545. },
  48546. set: function (value) {
  48547. var gamepad = this.inputs.attached["gamepad"];
  48548. if (gamepad)
  48549. gamepad.gamepadAngularSensibility = value;
  48550. },
  48551. enumerable: true,
  48552. configurable: true
  48553. });
  48554. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  48555. get: function () {
  48556. var gamepad = this.inputs.attached["gamepad"];
  48557. if (gamepad)
  48558. return gamepad.gamepadMoveSensibility;
  48559. },
  48560. set: function (value) {
  48561. var gamepad = this.inputs.attached["gamepad"];
  48562. if (gamepad)
  48563. gamepad.gamepadMoveSensibility = value;
  48564. },
  48565. enumerable: true,
  48566. configurable: true
  48567. });
  48568. GamepadCamera.prototype.getClassName = function () {
  48569. return "GamepadCamera";
  48570. };
  48571. return GamepadCamera;
  48572. }(BABYLON.UniversalCamera));
  48573. BABYLON.GamepadCamera = GamepadCamera;
  48574. })(BABYLON || (BABYLON = {}));
  48575. //# sourceMappingURL=babylon.gamepadCamera.js.map
  48576. var BABYLON;
  48577. (function (BABYLON) {
  48578. var PostProcessRenderPipelineManager = (function () {
  48579. function PostProcessRenderPipelineManager() {
  48580. this._renderPipelines = {};
  48581. }
  48582. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  48583. this._renderPipelines[renderPipeline._name] = renderPipeline;
  48584. };
  48585. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  48586. var renderPipeline = this._renderPipelines[renderPipelineName];
  48587. if (!renderPipeline) {
  48588. return;
  48589. }
  48590. renderPipeline._attachCameras(cameras, unique);
  48591. };
  48592. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  48593. var renderPipeline = this._renderPipelines[renderPipelineName];
  48594. if (!renderPipeline) {
  48595. return;
  48596. }
  48597. renderPipeline._detachCameras(cameras);
  48598. };
  48599. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48600. var renderPipeline = this._renderPipelines[renderPipelineName];
  48601. if (!renderPipeline) {
  48602. return;
  48603. }
  48604. renderPipeline._enableEffect(renderEffectName, cameras);
  48605. };
  48606. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  48607. var renderPipeline = this._renderPipelines[renderPipelineName];
  48608. if (!renderPipeline) {
  48609. return;
  48610. }
  48611. renderPipeline._disableEffect(renderEffectName, cameras);
  48612. };
  48613. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  48614. var renderPipeline = this._renderPipelines[renderPipelineName];
  48615. if (!renderPipeline) {
  48616. return;
  48617. }
  48618. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  48619. };
  48620. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  48621. var renderPipeline = this._renderPipelines[renderPipelineName];
  48622. if (!renderPipeline) {
  48623. return;
  48624. }
  48625. renderPipeline._disableDisplayOnlyPass(cameras);
  48626. };
  48627. PostProcessRenderPipelineManager.prototype.update = function () {
  48628. for (var renderPipelineName in this._renderPipelines) {
  48629. var pipeline = this._renderPipelines[renderPipelineName];
  48630. if (!pipeline.isSupported) {
  48631. pipeline.dispose();
  48632. delete this._renderPipelines[renderPipelineName];
  48633. }
  48634. else {
  48635. pipeline._update();
  48636. }
  48637. }
  48638. };
  48639. return PostProcessRenderPipelineManager;
  48640. }());
  48641. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  48642. })(BABYLON || (BABYLON = {}));
  48643. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  48644. var BABYLON;
  48645. (function (BABYLON) {
  48646. var PostProcessRenderPass = (function () {
  48647. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  48648. this._enabled = true;
  48649. this._refCount = 0;
  48650. this._name = name;
  48651. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  48652. this.setRenderList(renderList);
  48653. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  48654. this._renderTexture.onAfterRenderObservable.add(afterRender);
  48655. this._scene = scene;
  48656. this._renderList = renderList;
  48657. }
  48658. // private
  48659. PostProcessRenderPass.prototype._incRefCount = function () {
  48660. if (this._refCount === 0) {
  48661. this._scene.customRenderTargets.push(this._renderTexture);
  48662. }
  48663. return ++this._refCount;
  48664. };
  48665. PostProcessRenderPass.prototype._decRefCount = function () {
  48666. this._refCount--;
  48667. if (this._refCount <= 0) {
  48668. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  48669. }
  48670. return this._refCount;
  48671. };
  48672. PostProcessRenderPass.prototype._update = function () {
  48673. this.setRenderList(this._renderList);
  48674. };
  48675. // public
  48676. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  48677. this._renderTexture.renderList = renderList;
  48678. };
  48679. PostProcessRenderPass.prototype.getRenderTexture = function () {
  48680. return this._renderTexture;
  48681. };
  48682. return PostProcessRenderPass;
  48683. }());
  48684. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  48685. })(BABYLON || (BABYLON = {}));
  48686. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  48687. var BABYLON;
  48688. (function (BABYLON) {
  48689. var PostProcessRenderEffect = (function () {
  48690. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  48691. this._engine = engine;
  48692. this._name = name;
  48693. this._singleInstance = singleInstance || true;
  48694. this._getPostProcess = getPostProcess;
  48695. this._cameras = [];
  48696. this._indicesForCamera = [];
  48697. this._postProcesses = {};
  48698. this._renderPasses = {};
  48699. this._renderEffectAsPasses = {};
  48700. }
  48701. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  48702. get: function () {
  48703. for (var index in this._postProcesses) {
  48704. if (!this._postProcesses[index].isSupported) {
  48705. return false;
  48706. }
  48707. }
  48708. return true;
  48709. },
  48710. enumerable: true,
  48711. configurable: true
  48712. });
  48713. PostProcessRenderEffect.prototype._update = function () {
  48714. for (var renderPassName in this._renderPasses) {
  48715. this._renderPasses[renderPassName]._update();
  48716. }
  48717. };
  48718. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  48719. this._renderPasses[renderPass._name] = renderPass;
  48720. this._linkParameters();
  48721. };
  48722. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  48723. delete this._renderPasses[renderPass._name];
  48724. this._linkParameters();
  48725. };
  48726. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  48727. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  48728. this._linkParameters();
  48729. };
  48730. PostProcessRenderEffect.prototype.getPass = function (passName) {
  48731. for (var renderPassName in this._renderPasses) {
  48732. if (renderPassName === passName) {
  48733. return this._renderPasses[passName];
  48734. }
  48735. }
  48736. };
  48737. PostProcessRenderEffect.prototype.emptyPasses = function () {
  48738. this._renderPasses = {};
  48739. this._linkParameters();
  48740. };
  48741. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  48742. var cameraKey;
  48743. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48744. for (var i = 0; i < _cam.length; i++) {
  48745. var camera = _cam[i];
  48746. var cameraName = camera.name;
  48747. if (this._singleInstance) {
  48748. cameraKey = 0;
  48749. }
  48750. else {
  48751. cameraKey = cameraName;
  48752. }
  48753. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  48754. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  48755. if (!this._indicesForCamera[cameraName]) {
  48756. this._indicesForCamera[cameraName] = [];
  48757. }
  48758. this._indicesForCamera[cameraName].push(index);
  48759. if (this._cameras.indexOf(camera) === -1) {
  48760. this._cameras[cameraName] = camera;
  48761. }
  48762. for (var passName in this._renderPasses) {
  48763. this._renderPasses[passName]._incRefCount();
  48764. }
  48765. }
  48766. this._linkParameters();
  48767. };
  48768. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  48769. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48770. for (var i = 0; i < _cam.length; i++) {
  48771. var camera = _cam[i];
  48772. var cameraName = camera.name;
  48773. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48774. var index = this._cameras.indexOf(cameraName);
  48775. this._indicesForCamera.splice(index, 1);
  48776. this._cameras.splice(index, 1);
  48777. for (var passName in this._renderPasses) {
  48778. this._renderPasses[passName]._decRefCount();
  48779. }
  48780. }
  48781. };
  48782. PostProcessRenderEffect.prototype._enable = function (cameras) {
  48783. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48784. for (var i = 0; i < _cam.length; i++) {
  48785. var camera = _cam[i];
  48786. var cameraName = camera.name;
  48787. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  48788. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  48789. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  48790. }
  48791. }
  48792. for (var passName in this._renderPasses) {
  48793. this._renderPasses[passName]._incRefCount();
  48794. }
  48795. }
  48796. };
  48797. PostProcessRenderEffect.prototype._disable = function (cameras) {
  48798. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48799. for (var i = 0; i < _cam.length; i++) {
  48800. var camera = _cam[i];
  48801. var cameraName = camera.Name;
  48802. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  48803. for (var passName in this._renderPasses) {
  48804. this._renderPasses[passName]._decRefCount();
  48805. }
  48806. }
  48807. };
  48808. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  48809. if (this._singleInstance) {
  48810. return this._postProcesses[0];
  48811. }
  48812. else {
  48813. return this._postProcesses[camera.name];
  48814. }
  48815. };
  48816. PostProcessRenderEffect.prototype._linkParameters = function () {
  48817. var _this = this;
  48818. for (var index in this._postProcesses) {
  48819. if (this.applyParameters) {
  48820. this.applyParameters(this._postProcesses[index]);
  48821. }
  48822. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  48823. _this._linkTextures(effect);
  48824. });
  48825. }
  48826. };
  48827. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  48828. for (var renderPassName in this._renderPasses) {
  48829. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  48830. }
  48831. for (var renderEffectName in this._renderEffectAsPasses) {
  48832. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  48833. }
  48834. };
  48835. return PostProcessRenderEffect;
  48836. }());
  48837. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  48838. })(BABYLON || (BABYLON = {}));
  48839. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  48840. var BABYLON;
  48841. (function (BABYLON) {
  48842. var PostProcessRenderPipeline = (function () {
  48843. function PostProcessRenderPipeline(engine, name) {
  48844. this._engine = engine;
  48845. this._name = name;
  48846. this._renderEffects = new Array();
  48847. this._renderEffectsForIsolatedPass = new Array();
  48848. this._cameras = [];
  48849. }
  48850. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  48851. get: function () {
  48852. for (var renderEffectName in this._renderEffects) {
  48853. if (!this._renderEffects[renderEffectName].isSupported) {
  48854. return false;
  48855. }
  48856. }
  48857. return true;
  48858. },
  48859. enumerable: true,
  48860. configurable: true
  48861. });
  48862. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  48863. this._renderEffects[renderEffect._name] = renderEffect;
  48864. };
  48865. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  48866. var renderEffects = this._renderEffects[renderEffectName];
  48867. if (!renderEffects) {
  48868. return;
  48869. }
  48870. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48871. };
  48872. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  48873. var renderEffects = this._renderEffects[renderEffectName];
  48874. if (!renderEffects) {
  48875. return;
  48876. }
  48877. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  48878. };
  48879. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  48880. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48881. var indicesToDelete = [];
  48882. var i;
  48883. for (i = 0; i < _cam.length; i++) {
  48884. var camera = _cam[i];
  48885. var cameraName = camera.name;
  48886. if (this._cameras.indexOf(camera) === -1) {
  48887. this._cameras[cameraName] = camera;
  48888. }
  48889. else if (unique) {
  48890. indicesToDelete.push(i);
  48891. }
  48892. }
  48893. for (i = 0; i < indicesToDelete.length; i++) {
  48894. cameras.splice(indicesToDelete[i], 1);
  48895. }
  48896. for (var renderEffectName in this._renderEffects) {
  48897. this._renderEffects[renderEffectName]._attachCameras(_cam);
  48898. }
  48899. };
  48900. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  48901. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48902. for (var renderEffectName in this._renderEffects) {
  48903. this._renderEffects[renderEffectName]._detachCameras(_cam);
  48904. }
  48905. for (var i = 0; i < _cam.length; i++) {
  48906. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  48907. }
  48908. };
  48909. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  48910. var _this = this;
  48911. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48912. var pass = null;
  48913. var renderEffectName;
  48914. for (renderEffectName in this._renderEffects) {
  48915. pass = this._renderEffects[renderEffectName].getPass(passName);
  48916. if (pass != null) {
  48917. break;
  48918. }
  48919. }
  48920. if (pass === null) {
  48921. return;
  48922. }
  48923. for (renderEffectName in this._renderEffects) {
  48924. this._renderEffects[renderEffectName]._disable(_cam);
  48925. }
  48926. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  48927. for (var i = 0; i < _cam.length; i++) {
  48928. var camera = _cam[i];
  48929. var cameraName = camera.name;
  48930. 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); });
  48931. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  48932. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  48933. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  48934. }
  48935. };
  48936. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  48937. var _this = this;
  48938. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  48939. for (var i = 0; i < _cam.length; i++) {
  48940. var camera = _cam[i];
  48941. var cameraName = camera.name;
  48942. 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); });
  48943. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  48944. }
  48945. for (var renderEffectName in this._renderEffects) {
  48946. this._renderEffects[renderEffectName]._enable(_cam);
  48947. }
  48948. };
  48949. PostProcessRenderPipeline.prototype._update = function () {
  48950. for (var renderEffectName in this._renderEffects) {
  48951. this._renderEffects[renderEffectName]._update();
  48952. }
  48953. for (var i = 0; i < this._cameras.length; i++) {
  48954. var cameraName = this._cameras[i].name;
  48955. if (this._renderEffectsForIsolatedPass[cameraName]) {
  48956. this._renderEffectsForIsolatedPass[cameraName]._update();
  48957. }
  48958. }
  48959. };
  48960. PostProcessRenderPipeline.prototype._reset = function () {
  48961. this._renderEffects = new Array();
  48962. this._renderEffectsForIsolatedPass = new Array();
  48963. };
  48964. PostProcessRenderPipeline.prototype.dispose = function () {
  48965. // Must be implemented by children
  48966. };
  48967. return PostProcessRenderPipeline;
  48968. }());
  48969. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  48970. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  48971. __decorate([
  48972. BABYLON.serialize()
  48973. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  48974. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  48975. })(BABYLON || (BABYLON = {}));
  48976. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  48977. var BABYLON;
  48978. (function (BABYLON) {
  48979. var DepthRenderer = (function () {
  48980. function DepthRenderer(scene, type) {
  48981. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  48982. var _this = this;
  48983. this._viewMatrix = BABYLON.Matrix.Zero();
  48984. this._projectionMatrix = BABYLON.Matrix.Zero();
  48985. this._transformMatrix = BABYLON.Matrix.Zero();
  48986. this._worldViewProjection = BABYLON.Matrix.Zero();
  48987. this._scene = scene;
  48988. var engine = scene.getEngine();
  48989. // Render target
  48990. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  48991. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48992. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48993. this._depthMap.refreshRate = 1;
  48994. this._depthMap.renderParticles = false;
  48995. this._depthMap.renderList = null;
  48996. // set default depth value to 1.0 (far away)
  48997. this._depthMap.onClearObservable.add(function (engine) {
  48998. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  48999. });
  49000. // Custom render function
  49001. var renderSubMesh = function (subMesh) {
  49002. var mesh = subMesh.getRenderingMesh();
  49003. var scene = _this._scene;
  49004. var engine = scene.getEngine();
  49005. // Culling
  49006. engine.setState(subMesh.getMaterial().backFaceCulling);
  49007. // Managing instances
  49008. var batch = mesh._getInstancesRenderList(subMesh._id);
  49009. if (batch.mustReturn) {
  49010. return;
  49011. }
  49012. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  49013. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  49014. engine.enableEffect(_this._effect);
  49015. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  49016. var material = subMesh.getMaterial();
  49017. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  49018. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  49019. // Alpha test
  49020. if (material && material.needAlphaTesting()) {
  49021. var alphaTexture = material.getAlphaTestTexture();
  49022. _this._effect.setTexture("diffuseSampler", alphaTexture);
  49023. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  49024. }
  49025. // Bones
  49026. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49027. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49028. }
  49029. // Draw
  49030. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49031. }
  49032. };
  49033. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  49034. var index;
  49035. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49036. renderSubMesh(opaqueSubMeshes.data[index]);
  49037. }
  49038. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49039. renderSubMesh(alphaTestSubMeshes.data[index]);
  49040. }
  49041. };
  49042. }
  49043. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  49044. var material = subMesh.getMaterial();
  49045. if (material.disableDepthWrite) {
  49046. return false;
  49047. }
  49048. var defines = [];
  49049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49050. var mesh = subMesh.getMesh();
  49051. var scene = mesh.getScene();
  49052. // Alpha test
  49053. if (material && material.needAlphaTesting()) {
  49054. defines.push("#define ALPHATEST");
  49055. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49056. attribs.push(BABYLON.VertexBuffer.UVKind);
  49057. defines.push("#define UV1");
  49058. }
  49059. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49060. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49061. defines.push("#define UV2");
  49062. }
  49063. }
  49064. // Bones
  49065. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49066. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49067. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49068. if (mesh.numBoneInfluencers > 4) {
  49069. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49070. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49071. }
  49072. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49073. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49074. }
  49075. else {
  49076. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49077. }
  49078. // Instances
  49079. if (useInstances) {
  49080. defines.push("#define INSTANCES");
  49081. attribs.push("world0");
  49082. attribs.push("world1");
  49083. attribs.push("world2");
  49084. attribs.push("world3");
  49085. }
  49086. // Get correct effect
  49087. var join = defines.join("\n");
  49088. if (this._cachedDefines !== join) {
  49089. this._cachedDefines = join;
  49090. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  49091. }
  49092. return this._effect.isReady();
  49093. };
  49094. DepthRenderer.prototype.getDepthMap = function () {
  49095. return this._depthMap;
  49096. };
  49097. // Methods
  49098. DepthRenderer.prototype.dispose = function () {
  49099. this._depthMap.dispose();
  49100. };
  49101. return DepthRenderer;
  49102. }());
  49103. BABYLON.DepthRenderer = DepthRenderer;
  49104. })(BABYLON || (BABYLON = {}));
  49105. //# sourceMappingURL=babylon.depthRenderer.js.map
  49106. var BABYLON;
  49107. (function (BABYLON) {
  49108. var SSAORenderingPipeline = (function (_super) {
  49109. __extends(SSAORenderingPipeline, _super);
  49110. /**
  49111. * @constructor
  49112. * @param {string} name - The rendering pipeline name
  49113. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49114. * @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 }
  49115. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49116. */
  49117. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  49118. var _this = _super.call(this, scene.getEngine(), name) || this;
  49119. // Members
  49120. /**
  49121. * The PassPostProcess id in the pipeline that contains the original scene color
  49122. * @type {string}
  49123. */
  49124. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49125. /**
  49126. * The SSAO PostProcess id in the pipeline
  49127. * @type {string}
  49128. */
  49129. _this.SSAORenderEffect = "SSAORenderEffect";
  49130. /**
  49131. * The horizontal blur PostProcess id in the pipeline
  49132. * @type {string}
  49133. */
  49134. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49135. /**
  49136. * The vertical blur PostProcess id in the pipeline
  49137. * @type {string}
  49138. */
  49139. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49140. /**
  49141. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49142. * @type {string}
  49143. */
  49144. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49145. /**
  49146. * The output strength of the SSAO post-process. Default value is 1.0.
  49147. * @type {number}
  49148. */
  49149. _this.totalStrength = 1.0;
  49150. /**
  49151. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  49152. * @type {number}
  49153. */
  49154. _this.radius = 0.0001;
  49155. /**
  49156. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  49157. * Must not be equal to fallOff and superior to fallOff.
  49158. * Default value is 0.975
  49159. * @type {number}
  49160. */
  49161. _this.area = 0.0075;
  49162. /**
  49163. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  49164. * Must not be equal to area and inferior to area.
  49165. * Default value is 0.0
  49166. * @type {number}
  49167. */
  49168. _this.fallOff = 0.000001;
  49169. /**
  49170. * The base color of the SSAO post-process
  49171. * The final result is "base + ssao" between [0, 1]
  49172. * @type {number}
  49173. */
  49174. _this.base = 0.5;
  49175. _this._firstUpdate = true;
  49176. _this._scene = scene;
  49177. // Set up assets
  49178. _this._createRandomTexture();
  49179. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49180. var ssaoRatio = ratio.ssaoRatio || ratio;
  49181. var combineRatio = ratio.combineRatio || ratio;
  49182. _this._ratio = {
  49183. ssaoRatio: ssaoRatio,
  49184. combineRatio: combineRatio
  49185. };
  49186. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49187. _this._createSSAOPostProcess(ssaoRatio);
  49188. _this._createBlurPostProcess(ssaoRatio);
  49189. _this._createSSAOCombinePostProcess(combineRatio);
  49190. // Set up pipeline
  49191. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49192. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49193. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49194. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49195. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49196. // Finish
  49197. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49198. if (cameras)
  49199. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49200. return _this;
  49201. }
  49202. // Public Methods
  49203. /**
  49204. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49205. */
  49206. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49207. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49208. for (var i = 0; i < this._scene.cameras.length; i++) {
  49209. var camera = this._scene.cameras[i];
  49210. this._originalColorPostProcess.dispose(camera);
  49211. this._ssaoPostProcess.dispose(camera);
  49212. this._blurHPostProcess.dispose(camera);
  49213. this._blurVPostProcess.dispose(camera);
  49214. this._ssaoCombinePostProcess.dispose(camera);
  49215. }
  49216. this._randomTexture.dispose();
  49217. if (disableDepthRender)
  49218. this._scene.disableDepthRenderer();
  49219. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49220. _super.prototype.dispose.call(this);
  49221. };
  49222. // Private Methods
  49223. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  49224. var _this = this;
  49225. /*
  49226. var samplerOffsets = [
  49227. -8.0, -6.0, -4.0, -2.0,
  49228. 0.0,
  49229. 2.0, 4.0, 6.0, 8.0
  49230. ];
  49231. */
  49232. var samples = 16;
  49233. var samplerOffsets = [];
  49234. for (var i = -8; i < 8; i++) {
  49235. samplerOffsets.push(i * 2);
  49236. }
  49237. 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");
  49238. this._blurHPostProcess.onApply = function (effect) {
  49239. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49240. effect.setTexture("depthSampler", _this._depthTexture);
  49241. if (_this._firstUpdate) {
  49242. effect.setArray("samplerOffsets", samplerOffsets);
  49243. }
  49244. };
  49245. 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");
  49246. this._blurVPostProcess.onApply = function (effect) {
  49247. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49248. effect.setTexture("depthSampler", _this._depthTexture);
  49249. if (_this._firstUpdate) {
  49250. effect.setArray("samplerOffsets", samplerOffsets);
  49251. _this._firstUpdate = false;
  49252. }
  49253. };
  49254. };
  49255. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49256. var _this = this;
  49257. var numSamples = 16;
  49258. var sampleSphere = [
  49259. 0.5381, 0.1856, -0.4319,
  49260. 0.1379, 0.2486, 0.4430,
  49261. 0.3371, 0.5679, -0.0057,
  49262. -0.6999, -0.0451, -0.0019,
  49263. 0.0689, -0.1598, -0.8547,
  49264. 0.0560, 0.0069, -0.1843,
  49265. -0.0146, 0.1402, 0.0762,
  49266. 0.0100, -0.1924, -0.0344,
  49267. -0.3577, -0.5301, -0.4358,
  49268. -0.3169, 0.1063, 0.0158,
  49269. 0.0103, -0.5869, 0.0046,
  49270. -0.0897, -0.4940, 0.3287,
  49271. 0.7119, -0.0154, -0.0918,
  49272. -0.0533, 0.0596, -0.5411,
  49273. 0.0352, -0.0631, 0.5460,
  49274. -0.4776, 0.2847, -0.0271
  49275. ];
  49276. var samplesFactor = 1.0 / numSamples;
  49277. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  49278. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49279. "area", "fallOff", "base", "range", "viewport"
  49280. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49281. var viewport = new BABYLON.Vector2(0, 0);
  49282. this._ssaoPostProcess.onApply = function (effect) {
  49283. if (_this._firstUpdate) {
  49284. effect.setArray3("sampleSphere", sampleSphere);
  49285. effect.setFloat("samplesFactor", samplesFactor);
  49286. effect.setFloat("randTextureTiles", 4.0);
  49287. }
  49288. effect.setFloat("totalStrength", _this.totalStrength);
  49289. effect.setFloat("radius", _this.radius);
  49290. effect.setFloat("area", _this.area);
  49291. effect.setFloat("fallOff", _this.fallOff);
  49292. effect.setFloat("base", _this.base);
  49293. effect.setTexture("textureSampler", _this._depthTexture);
  49294. effect.setTexture("randomSampler", _this._randomTexture);
  49295. };
  49296. };
  49297. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49298. var _this = this;
  49299. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49300. this._ssaoCombinePostProcess.onApply = function (effect) {
  49301. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49302. };
  49303. };
  49304. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  49305. var size = 512;
  49306. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49307. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49308. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49309. var context = this._randomTexture.getContext();
  49310. var rand = function (min, max) {
  49311. return Math.random() * (max - min) + min;
  49312. };
  49313. var randVector = BABYLON.Vector3.Zero();
  49314. for (var x = 0; x < size; x++) {
  49315. for (var y = 0; y < size; y++) {
  49316. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  49317. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  49318. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  49319. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49320. context.fillRect(x, y, 1, 1);
  49321. }
  49322. }
  49323. this._randomTexture.update(false);
  49324. };
  49325. return SSAORenderingPipeline;
  49326. }(BABYLON.PostProcessRenderPipeline));
  49327. __decorate([
  49328. BABYLON.serialize()
  49329. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  49330. __decorate([
  49331. BABYLON.serialize()
  49332. ], SSAORenderingPipeline.prototype, "radius", void 0);
  49333. __decorate([
  49334. BABYLON.serialize()
  49335. ], SSAORenderingPipeline.prototype, "area", void 0);
  49336. __decorate([
  49337. BABYLON.serialize()
  49338. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  49339. __decorate([
  49340. BABYLON.serialize()
  49341. ], SSAORenderingPipeline.prototype, "base", void 0);
  49342. __decorate([
  49343. BABYLON.serialize()
  49344. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  49345. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  49346. })(BABYLON || (BABYLON = {}));
  49347. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  49348. var BABYLON;
  49349. (function (BABYLON) {
  49350. var SSAO2RenderingPipeline = (function (_super) {
  49351. __extends(SSAO2RenderingPipeline, _super);
  49352. /**
  49353. * @constructor
  49354. * @param {string} name - The rendering pipeline name
  49355. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49356. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  49357. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49358. */
  49359. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  49360. var _this = _super.call(this, scene.getEngine(), name) || this;
  49361. // Members
  49362. /**
  49363. * The PassPostProcess id in the pipeline that contains the original scene color
  49364. * @type {string}
  49365. */
  49366. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  49367. /**
  49368. * The SSAO PostProcess id in the pipeline
  49369. * @type {string}
  49370. */
  49371. _this.SSAORenderEffect = "SSAORenderEffect";
  49372. /**
  49373. * The horizontal blur PostProcess id in the pipeline
  49374. * @type {string}
  49375. */
  49376. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  49377. /**
  49378. * The vertical blur PostProcess id in the pipeline
  49379. * @type {string}
  49380. */
  49381. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  49382. /**
  49383. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  49384. * @type {string}
  49385. */
  49386. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  49387. /**
  49388. * The output strength of the SSAO post-process. Default value is 1.0.
  49389. * @type {number}
  49390. */
  49391. _this.totalStrength = 1.0;
  49392. /**
  49393. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  49394. * @type {number}
  49395. */
  49396. _this.maxZ = 100.0;
  49397. /**
  49398. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  49399. * @type {number}
  49400. */
  49401. _this.minZAspect = 0.2;
  49402. /**
  49403. * Number of samples used for the SSAO calculations. Default value is 8
  49404. * @type {number}
  49405. */
  49406. _this._samples = 8;
  49407. /**
  49408. * Are we using bilateral blur ?
  49409. * @type {boolean}
  49410. */
  49411. _this._expensiveBlur = true;
  49412. /**
  49413. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  49414. * @type {number}
  49415. */
  49416. _this.radius = 2.0;
  49417. /**
  49418. * The base color of the SSAO post-process
  49419. * The final result is "base + ssao" between [0, 1]
  49420. * @type {number}
  49421. */
  49422. _this.base = 0.1;
  49423. _this._firstUpdate = true;
  49424. _this._scene = scene;
  49425. if (!_this.isSupported) {
  49426. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  49427. return _this;
  49428. }
  49429. var ssaoRatio = ratio.ssaoRatio || ratio;
  49430. var blurRatio = ratio.blurRatio || ratio;
  49431. _this._ratio = {
  49432. ssaoRatio: ssaoRatio,
  49433. blurRatio: blurRatio
  49434. };
  49435. // Set up assets
  49436. _this._createRandomTexture();
  49437. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  49438. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  49439. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49440. _this._createSSAOPostProcess(1.0);
  49441. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  49442. _this._createSSAOCombinePostProcess(blurRatio);
  49443. // Set up pipeline
  49444. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  49445. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  49446. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  49447. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  49448. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  49449. // Finish
  49450. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49451. if (cameras)
  49452. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49453. return _this;
  49454. }
  49455. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  49456. get: function () {
  49457. return this._samples;
  49458. },
  49459. set: function (n) {
  49460. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  49461. this._samples = n;
  49462. this._sampleSphere = this._generateHemisphere();
  49463. this._firstUpdate = true;
  49464. },
  49465. enumerable: true,
  49466. configurable: true
  49467. });
  49468. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  49469. get: function () {
  49470. return this._expensiveBlur;
  49471. },
  49472. set: function (b) {
  49473. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49474. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  49475. this._expensiveBlur = b;
  49476. this._firstUpdate = true;
  49477. },
  49478. enumerable: true,
  49479. configurable: true
  49480. });
  49481. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  49482. /**
  49483. * Support test.
  49484. * @type {boolean}
  49485. */
  49486. get: function () {
  49487. var engine = BABYLON.Engine.LastCreatedEngine;
  49488. return engine.webGLVersion > 1;
  49489. },
  49490. enumerable: true,
  49491. configurable: true
  49492. });
  49493. // Public Methods
  49494. /**
  49495. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  49496. */
  49497. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  49498. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  49499. for (var i = 0; i < this._scene.cameras.length; i++) {
  49500. var camera = this._scene.cameras[i];
  49501. this._originalColorPostProcess.dispose(camera);
  49502. this._ssaoPostProcess.dispose(camera);
  49503. this._blurHPostProcess.dispose(camera);
  49504. this._blurVPostProcess.dispose(camera);
  49505. this._ssaoCombinePostProcess.dispose(camera);
  49506. }
  49507. this._randomTexture.dispose();
  49508. if (disableGeometryBufferRenderer)
  49509. this._scene.disableGeometryBufferRenderer();
  49510. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49511. _super.prototype.dispose.call(this);
  49512. };
  49513. // Private Methods
  49514. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  49515. var _this = this;
  49516. var samples = 16;
  49517. this._samplerOffsets = [];
  49518. var expensive = this.expensiveBlur;
  49519. for (var i = -8; i < 8; i++) {
  49520. this._samplerOffsets.push(i * 2 + 0.5);
  49521. }
  49522. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  49523. this._blurHPostProcess.onApply = function (effect) {
  49524. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  49525. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49526. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49527. effect.setFloat("radius", _this.radius);
  49528. effect.setTexture("depthSampler", _this._depthTexture);
  49529. if (_this._firstUpdate) {
  49530. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49531. }
  49532. };
  49533. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  49534. this._blurVPostProcess.onApply = function (effect) {
  49535. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  49536. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49537. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49538. effect.setFloat("radius", _this.radius);
  49539. effect.setTexture("depthSampler", _this._depthTexture);
  49540. if (_this._firstUpdate) {
  49541. effect.setArray("samplerOffsets", _this._samplerOffsets);
  49542. _this._firstUpdate = false;
  49543. }
  49544. };
  49545. };
  49546. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  49547. var numSamples = this.samples;
  49548. var result = [];
  49549. var vector, scale;
  49550. var rand = function (min, max) {
  49551. return Math.random() * (max - min) + min;
  49552. };
  49553. var lerp = function (start, end, percent) {
  49554. return (start + percent * (end - start));
  49555. };
  49556. var i = 0;
  49557. var normal = new BABYLON.Vector3(0, 0, 1);
  49558. while (i < numSamples) {
  49559. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  49560. vector.normalize();
  49561. scale = i / numSamples;
  49562. scale = lerp(0.1, 1.0, scale * scale);
  49563. vector.scaleInPlace(scale);
  49564. result.push(vector.x, vector.y, vector.z);
  49565. i++;
  49566. }
  49567. return result;
  49568. };
  49569. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  49570. var _this = this;
  49571. var numSamples = this.samples;
  49572. this._sampleSphere = this._generateHemisphere();
  49573. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  49574. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  49575. "base", "range", "projection", "near", "far", "texelSize",
  49576. "xViewport", "yViewport", "maxZ", "minZAspect"
  49577. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  49578. this._ssaoPostProcess.onApply = function (effect) {
  49579. if (_this._firstUpdate) {
  49580. effect.setArray3("sampleSphere", _this._sampleSphere);
  49581. effect.setFloat("randTextureTiles", 4.0);
  49582. }
  49583. effect.setFloat("samplesFactor", 1 / _this.samples);
  49584. effect.setFloat("totalStrength", _this.totalStrength);
  49585. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  49586. effect.setFloat("radius", _this.radius);
  49587. effect.setFloat("maxZ", _this.maxZ);
  49588. effect.setFloat("minZAspect", _this.minZAspect);
  49589. effect.setFloat("base", _this.base);
  49590. effect.setFloat("near", _this._scene.activeCamera.minZ);
  49591. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  49592. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  49593. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.activeCamera.minZ);
  49594. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  49595. effect.setTexture("textureSampler", _this._depthTexture);
  49596. effect.setTexture("normalSampler", _this._normalTexture);
  49597. effect.setTexture("randomSampler", _this._randomTexture);
  49598. };
  49599. };
  49600. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  49601. var _this = this;
  49602. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49603. this._ssaoCombinePostProcess.onApply = function (effect) {
  49604. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  49605. };
  49606. };
  49607. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  49608. var size = 512;
  49609. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  49610. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49611. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49612. var context = this._randomTexture.getContext();
  49613. var rand = function (min, max) {
  49614. return Math.random() * (max - min) + min;
  49615. };
  49616. var randVector = BABYLON.Vector3.Zero();
  49617. for (var x = 0; x < size; x++) {
  49618. for (var y = 0; y < size; y++) {
  49619. randVector.x = rand(0.0, 1.0);
  49620. randVector.y = rand(0.0, 1.0);
  49621. randVector.z = 0.0;
  49622. randVector.normalize();
  49623. randVector.scaleInPlace(255);
  49624. randVector.x = Math.floor(randVector.x);
  49625. randVector.y = Math.floor(randVector.y);
  49626. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  49627. context.fillRect(x, y, 1, 1);
  49628. }
  49629. }
  49630. this._randomTexture.update(false);
  49631. };
  49632. return SSAO2RenderingPipeline;
  49633. }(BABYLON.PostProcessRenderPipeline));
  49634. __decorate([
  49635. BABYLON.serialize()
  49636. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  49637. __decorate([
  49638. BABYLON.serialize()
  49639. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  49640. __decorate([
  49641. BABYLON.serialize()
  49642. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  49643. __decorate([
  49644. BABYLON.serialize("samples")
  49645. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  49646. __decorate([
  49647. BABYLON.serialize("expensiveBlur")
  49648. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  49649. __decorate([
  49650. BABYLON.serialize()
  49651. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  49652. __decorate([
  49653. BABYLON.serialize()
  49654. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  49655. __decorate([
  49656. BABYLON.serialize()
  49657. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  49658. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  49659. })(BABYLON || (BABYLON = {}));
  49660. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  49661. // BABYLON.JS Chromatic Aberration GLSL Shader
  49662. // Author: Olivier Guyot
  49663. // Separates very slightly R, G and B colors on the edges of the screen
  49664. // Inspired by Francois Tarlier & Martins Upitis
  49665. var BABYLON;
  49666. (function (BABYLON) {
  49667. var LensRenderingPipeline = (function (_super) {
  49668. __extends(LensRenderingPipeline, _super);
  49669. /**
  49670. * @constructor
  49671. *
  49672. * Effect parameters are as follow:
  49673. * {
  49674. * chromatic_aberration: number; // from 0 to x (1 for realism)
  49675. * edge_blur: number; // from 0 to x (1 for realism)
  49676. * distortion: number; // from 0 to x (1 for realism)
  49677. * grain_amount: number; // from 0 to 1
  49678. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  49679. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  49680. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  49681. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  49682. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  49683. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  49684. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  49685. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  49686. * }
  49687. * Note: if an effect parameter is unset, effect is disabled
  49688. *
  49689. * @param {string} name - The rendering pipeline name
  49690. * @param {object} parameters - An object containing all parameters (see above)
  49691. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49692. * @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)
  49693. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49694. */
  49695. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  49696. if (ratio === void 0) { ratio = 1.0; }
  49697. var _this = _super.call(this, scene.getEngine(), name) || this;
  49698. // Lens effects can be of the following:
  49699. // - chromatic aberration (slight shift of RGB colors)
  49700. // - blur on the edge of the lens
  49701. // - lens distortion
  49702. // - depth-of-field blur & highlights enhancing
  49703. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  49704. // - grain effect (noise or custom texture)
  49705. // Two additional texture samplers are needed:
  49706. // - depth map (for depth-of-field)
  49707. // - grain texture
  49708. /**
  49709. * The chromatic aberration PostProcess id in the pipeline
  49710. * @type {string}
  49711. */
  49712. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  49713. /**
  49714. * The highlights enhancing PostProcess id in the pipeline
  49715. * @type {string}
  49716. */
  49717. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  49718. /**
  49719. * The depth-of-field PostProcess id in the pipeline
  49720. * @type {string}
  49721. */
  49722. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  49723. _this._scene = scene;
  49724. // Fetch texture samplers
  49725. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  49726. if (parameters.grain_texture) {
  49727. _this._grainTexture = parameters.grain_texture;
  49728. }
  49729. else {
  49730. _this._createGrainTexture();
  49731. }
  49732. // save parameters
  49733. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  49734. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  49735. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  49736. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  49737. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  49738. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  49739. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  49740. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  49741. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  49742. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  49743. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  49744. // Create effects
  49745. _this._createChromaticAberrationPostProcess(ratio);
  49746. _this._createHighlightsPostProcess(ratio);
  49747. _this._createDepthOfFieldPostProcess(ratio / 4);
  49748. // Set up pipeline
  49749. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  49750. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  49751. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  49752. if (_this._highlightsGain === -1) {
  49753. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  49754. }
  49755. // Finish
  49756. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49757. if (cameras) {
  49758. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49759. }
  49760. return _this;
  49761. }
  49762. // public methods (self explanatory)
  49763. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  49764. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  49765. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  49766. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  49767. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  49768. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  49769. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  49770. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  49771. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  49772. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  49773. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  49774. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  49775. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  49776. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  49777. };
  49778. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  49779. this._highlightsPostProcess.updateEffect();
  49780. };
  49781. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  49782. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  49783. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  49784. this._highlightsGain = amount;
  49785. };
  49786. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  49787. if (this._highlightsGain === -1) {
  49788. this._highlightsGain = 1.0;
  49789. }
  49790. this._highlightsThreshold = amount;
  49791. };
  49792. LensRenderingPipeline.prototype.disableHighlights = function () {
  49793. this._highlightsGain = -1;
  49794. };
  49795. /**
  49796. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  49797. */
  49798. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  49799. if (disableDepthRender === void 0) { disableDepthRender = false; }
  49800. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49801. this._chromaticAberrationPostProcess = undefined;
  49802. this._highlightsPostProcess = undefined;
  49803. this._depthOfFieldPostProcess = undefined;
  49804. this._grainTexture.dispose();
  49805. if (disableDepthRender)
  49806. this._scene.disableDepthRenderer();
  49807. };
  49808. // colors shifting and distortion
  49809. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  49810. var _this = this;
  49811. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  49812. [], // samplers
  49813. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49814. this._chromaticAberrationPostProcess.onApply = function (effect) {
  49815. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  49816. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49817. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49818. };
  49819. };
  49820. // highlights enhancing
  49821. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  49822. var _this = this;
  49823. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  49824. [], // samplers
  49825. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  49826. this._highlightsPostProcess.onApply = function (effect) {
  49827. effect.setFloat('gain', _this._highlightsGain);
  49828. effect.setFloat('threshold', _this._highlightsThreshold);
  49829. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  49830. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49831. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49832. };
  49833. };
  49834. // colors shifting and distortion
  49835. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  49836. var _this = this;
  49837. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  49838. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  49839. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  49840. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  49841. this._depthOfFieldPostProcess.onApply = function (effect) {
  49842. effect.setTexture("depthSampler", _this._depthTexture);
  49843. effect.setTexture("grainSampler", _this._grainTexture);
  49844. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  49845. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  49846. effect.setFloat('grain_amount', _this._grainAmount);
  49847. effect.setBool('blur_noise', _this._blurNoise);
  49848. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  49849. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  49850. effect.setFloat('distortion', _this._distortion);
  49851. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  49852. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  49853. effect.setFloat('aperture', _this._dofAperture);
  49854. effect.setFloat('darken', _this._dofDarken);
  49855. effect.setFloat('edge_blur', _this._edgeBlur);
  49856. effect.setBool('highlights', (_this._highlightsGain !== -1));
  49857. effect.setFloat('near', _this._scene.activeCamera.minZ);
  49858. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  49859. };
  49860. };
  49861. // creates a black and white random noise texture, 512x512
  49862. LensRenderingPipeline.prototype._createGrainTexture = function () {
  49863. var size = 512;
  49864. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49865. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  49866. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  49867. var context = this._grainTexture.getContext();
  49868. var rand = function (min, max) {
  49869. return Math.random() * (max - min) + min;
  49870. };
  49871. var value;
  49872. for (var x = 0; x < size; x++) {
  49873. for (var y = 0; y < size; y++) {
  49874. value = Math.floor(rand(0.42, 0.58) * 255);
  49875. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  49876. context.fillRect(x, y, 1, 1);
  49877. }
  49878. }
  49879. this._grainTexture.update(false);
  49880. };
  49881. return LensRenderingPipeline;
  49882. }(BABYLON.PostProcessRenderPipeline));
  49883. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  49884. })(BABYLON || (BABYLON = {}));
  49885. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  49886. var BABYLON;
  49887. (function (BABYLON) {
  49888. var StandardRenderingPipeline = (function (_super) {
  49889. __extends(StandardRenderingPipeline, _super);
  49890. /**
  49891. * @constructor
  49892. * @param {string} name - The rendering pipeline name
  49893. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49894. * @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)
  49895. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  49896. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49897. */
  49898. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  49899. if (originalPostProcess === void 0) { originalPostProcess = null; }
  49900. var _this = _super.call(this, scene.getEngine(), name) || this;
  49901. _this.downSampleX4PostProcess = null;
  49902. _this.brightPassPostProcess = null;
  49903. _this.gaussianBlurHPostProcesses = [];
  49904. _this.gaussianBlurVPostProcesses = [];
  49905. _this.textureAdderPostProcess = null;
  49906. _this.luminancePostProcess = null;
  49907. _this.luminanceDownSamplePostProcesses = [];
  49908. _this.hdrPostProcess = null;
  49909. _this.textureAdderFinalPostProcess = null;
  49910. _this.lensFlareFinalPostProcess = null;
  49911. _this.hdrFinalPostProcess = null;
  49912. _this.lensFlarePostProcess = null;
  49913. _this.lensFlareComposePostProcess = null;
  49914. _this.motionBlurPostProcess = null;
  49915. _this.depthOfFieldPostProcess = null;
  49916. // Values
  49917. _this.brightThreshold = 1.0;
  49918. _this.blurWidth = 2.0;
  49919. _this.horizontalBlur = false;
  49920. _this.gaussianCoefficient = 0.25;
  49921. _this.gaussianMean = 1.0;
  49922. _this.gaussianStandardDeviation = 1.0;
  49923. _this.exposure = 1.0;
  49924. _this.lensTexture = null;
  49925. _this.hdrMinimumLuminance = 1.0;
  49926. _this.hdrDecreaseRate = 0.5;
  49927. _this.hdrIncreaseRate = 0.5;
  49928. _this.lensColorTexture = null;
  49929. _this.lensFlareStrength = 20.0;
  49930. _this.lensFlareGhostDispersal = 1.4;
  49931. _this.lensFlareHaloWidth = 0.7;
  49932. _this.lensFlareDistortionStrength = 16.0;
  49933. _this.lensStarTexture = null;
  49934. _this.lensFlareDirtTexture = null;
  49935. _this.depthOfFieldDistance = 10.0;
  49936. _this.depthOfFieldBlurWidth = 2.0;
  49937. _this.motionStrength = 1.0;
  49938. // IAnimatable
  49939. _this.animations = [];
  49940. _this._depthRenderer = null;
  49941. _this._currentDepthOfFieldSource = null;
  49942. _this._currentHDRSource = null;
  49943. _this._hdrCurrentLuminance = 1.0;
  49944. _this._motionBlurSamples = 64;
  49945. // Getters and setters
  49946. _this._bloomEnabled = true;
  49947. _this._depthOfFieldEnabled = true;
  49948. _this._lensFlareEnabled = true;
  49949. _this._hdrEnabled = true;
  49950. _this._motionBlurEnabled = true;
  49951. _this._cameras = cameras || [];
  49952. // Initialize
  49953. _this._scene = scene;
  49954. // Misc
  49955. var floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49956. // Create pass post-process
  49957. if (!originalPostProcess) {
  49958. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", floatTextureType);
  49959. }
  49960. else {
  49961. _this.originalPostProcess = originalPostProcess;
  49962. }
  49963. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  49964. // Create down sample X4 post-process
  49965. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  49966. // Create bright pass post-process
  49967. _this._createBrightPassPostProcess(scene, ratio / 2);
  49968. // Create gaussian blur post-processes (down sampling blurs)
  49969. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  49970. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  49971. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  49972. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  49973. // Create texture adder post-process
  49974. _this._createTextureAdderPostProcess(scene, ratio);
  49975. // Create depth-of-field source post-process
  49976. _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);
  49977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  49978. // Create lens flare post-process
  49979. _this._createLensFlarePostProcess(scene, ratio);
  49980. // Create depth-of-field source post-process post lens-flare and disable it now
  49981. _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);
  49982. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  49983. // Create luminance
  49984. _this._createLuminancePostProcesses(scene, floatTextureType);
  49985. // Create HDR
  49986. _this._createHdrPostProcess(scene, ratio);
  49987. // Create depth-of-field source post-process post hdr and disable it now
  49988. _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);
  49989. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  49990. // Create gaussian blur used by depth-of-field
  49991. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  49992. // Create depth-of-field post-process
  49993. _this._createDepthOfFieldPostProcess(scene, ratio);
  49994. // Create motion blur post-process
  49995. _this._createMotionBlurPostProcess(scene, ratio);
  49996. // Finish
  49997. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49998. if (cameras !== null) {
  49999. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  50000. }
  50001. // Deactivate
  50002. _this.LensFlareEnabled = false;
  50003. _this.DepthOfFieldEnabled = false;
  50004. _this.HDREnabled = false;
  50005. _this.MotionBlurEnabled = false;
  50006. return _this;
  50007. }
  50008. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  50009. get: function () {
  50010. return this._bloomEnabled;
  50011. },
  50012. set: function (enabled) {
  50013. if (enabled && !this._bloomEnabled) {
  50014. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDownSampleX4", this._cameras);
  50015. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRBrightPass", this._cameras);
  50016. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  50017. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._cameras);
  50018. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._cameras);
  50019. }
  50020. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRTextureAdder", this._cameras);
  50021. }
  50022. else if (!enabled && this._bloomEnabled) {
  50023. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDownSampleX4", this._cameras);
  50024. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRBrightPass", this._cameras);
  50025. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  50026. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._cameras);
  50027. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._cameras);
  50028. }
  50029. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRTextureAdder", this._cameras);
  50030. }
  50031. this._bloomEnabled = enabled;
  50032. },
  50033. enumerable: true,
  50034. configurable: true
  50035. });
  50036. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  50037. get: function () {
  50038. return this._depthOfFieldEnabled;
  50039. },
  50040. set: function (enabled) {
  50041. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  50042. if (enabled && !this._depthOfFieldEnabled) {
  50043. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  50044. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  50045. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  50046. this._depthRenderer = this._scene.enableDepthRenderer();
  50047. }
  50048. else if (!enabled && this._depthOfFieldEnabled) {
  50049. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  50050. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  50051. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  50052. }
  50053. this._depthOfFieldEnabled = enabled;
  50054. },
  50055. enumerable: true,
  50056. configurable: true
  50057. });
  50058. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  50059. get: function () {
  50060. return this._lensFlareEnabled;
  50061. },
  50062. set: function (enabled) {
  50063. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  50064. if (enabled && !this._lensFlareEnabled) {
  50065. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  50066. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  50067. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  50068. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  50069. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  50070. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  50071. }
  50072. else if (!enabled && this._lensFlareEnabled) {
  50073. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  50074. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  50075. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  50076. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  50077. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  50078. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  50079. }
  50080. this._lensFlareEnabled = enabled;
  50081. },
  50082. enumerable: true,
  50083. configurable: true
  50084. });
  50085. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  50086. get: function () {
  50087. return this._hdrEnabled;
  50088. },
  50089. set: function (enabled) {
  50090. if (enabled && !this._hdrEnabled) {
  50091. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  50092. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  50093. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  50094. }
  50095. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  50096. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  50097. }
  50098. else if (!enabled && this._hdrEnabled) {
  50099. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  50100. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  50101. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  50102. }
  50103. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  50104. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  50105. }
  50106. this._hdrEnabled = enabled;
  50107. },
  50108. enumerable: true,
  50109. configurable: true
  50110. });
  50111. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  50112. get: function () {
  50113. return this._motionBlurEnabled;
  50114. },
  50115. set: function (enabled) {
  50116. if (enabled && !this._motionBlurEnabled) {
  50117. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  50118. this._depthRenderer = this._scene.enableDepthRenderer();
  50119. }
  50120. else if (!enabled && this._motionBlurEnabled) {
  50121. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRMotionBlur", this._scene.cameras);
  50122. }
  50123. this._motionBlurEnabled = enabled;
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  50129. get: function () {
  50130. return this._motionBlurSamples;
  50131. },
  50132. set: function (samples) {
  50133. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  50134. this._motionBlurSamples = samples;
  50135. },
  50136. enumerable: true,
  50137. configurable: true
  50138. });
  50139. // Down Sample X4 Post-Processs
  50140. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  50141. var _this = this;
  50142. var downSampleX4Offsets = new Array(32);
  50143. 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);
  50144. this.downSampleX4PostProcess.onApply = function (effect) {
  50145. var id = 0;
  50146. for (var i = -2; i < 2; i++) {
  50147. for (var j = -2; j < 2; j++) {
  50148. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  50149. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  50150. id += 2;
  50151. }
  50152. }
  50153. effect.setArray2("dsOffsets", downSampleX4Offsets);
  50154. };
  50155. // Add to pipeline
  50156. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  50157. };
  50158. // Brightpass Post-Process
  50159. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  50160. var _this = this;
  50161. var brightOffsets = new Array(8);
  50162. 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);
  50163. this.brightPassPostProcess.onApply = function (effect) {
  50164. var sU = (1.0 / _this.brightPassPostProcess.width);
  50165. var sV = (1.0 / _this.brightPassPostProcess.height);
  50166. brightOffsets[0] = -0.5 * sU;
  50167. brightOffsets[1] = 0.5 * sV;
  50168. brightOffsets[2] = 0.5 * sU;
  50169. brightOffsets[3] = 0.5 * sV;
  50170. brightOffsets[4] = -0.5 * sU;
  50171. brightOffsets[5] = -0.5 * sV;
  50172. brightOffsets[6] = 0.5 * sU;
  50173. brightOffsets[7] = -0.5 * sV;
  50174. effect.setArray2("dsOffsets", brightOffsets);
  50175. effect.setFloat("brightThreshold", _this.brightThreshold);
  50176. };
  50177. // Add to pipeline
  50178. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  50179. };
  50180. // Create gaussian blur H&V post-processes
  50181. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  50182. var _this = this;
  50183. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  50184. var blurOffsets = new Array(9);
  50185. var blurWeights = new Array(9);
  50186. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  50187. var callback = function (height) {
  50188. return function (effect) {
  50189. // Weights
  50190. var x = 0.0;
  50191. for (var i = 0; i < 9; i++) {
  50192. x = (i - 4.0) / 4.0;
  50193. blurWeights[i] =
  50194. _this.gaussianCoefficient
  50195. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  50196. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  50197. }
  50198. var lastOutputDimensions = {
  50199. width: scene.getEngine().getRenderWidth(),
  50200. height: scene.getEngine().getRenderHeight()
  50201. };
  50202. for (var i = 0; i < 9; i++) {
  50203. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  50204. blurOffsets[i] = value;
  50205. }
  50206. effect.setArray("blurOffsets", blurOffsets);
  50207. effect.setArray("blurWeights", blurWeights);
  50208. if (height) {
  50209. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  50210. }
  50211. else {
  50212. effect.setFloat("blurWidth", _this[blurWidthKey]);
  50213. }
  50214. };
  50215. };
  50216. // Create horizontal gaussian blur post-processes
  50217. 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);
  50218. gaussianBlurHPostProcess.onApply = callback(false);
  50219. // Create vertical gaussian blur post-process
  50220. 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);
  50221. gaussianBlurVPostProcess.onApply = callback(true);
  50222. // Add to pipeline
  50223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  50224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  50225. // Finish
  50226. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  50227. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  50228. };
  50229. // Create texture adder post-process
  50230. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  50231. var _this = this;
  50232. 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);
  50233. this.textureAdderPostProcess.onApply = function (effect) {
  50234. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  50235. effect.setTexture("lensSampler", _this.lensTexture);
  50236. effect.setFloat("exposure", _this.exposure);
  50237. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  50238. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  50239. };
  50240. // Add to pipeline
  50241. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  50242. };
  50243. // Create luminance
  50244. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  50245. var _this = this;
  50246. // Create luminance
  50247. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  50248. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  50249. var offsets = [];
  50250. this.luminancePostProcess.onApply = function (effect) {
  50251. var sU = (1.0 / _this.luminancePostProcess.width);
  50252. var sV = (1.0 / _this.luminancePostProcess.height);
  50253. offsets[0] = -0.5 * sU;
  50254. offsets[1] = 0.5 * sV;
  50255. offsets[2] = 0.5 * sU;
  50256. offsets[3] = 0.5 * sV;
  50257. offsets[4] = -0.5 * sU;
  50258. offsets[5] = -0.5 * sV;
  50259. offsets[6] = 0.5 * sU;
  50260. offsets[7] = -0.5 * sV;
  50261. effect.setArray2("lumOffsets", offsets);
  50262. };
  50263. // Add to pipeline
  50264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  50265. // Create down sample luminance
  50266. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  50267. var size = Math.pow(3, i);
  50268. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  50269. if (i === 0) {
  50270. defines += "#define FINAL_DOWN_SAMPLER";
  50271. }
  50272. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  50273. this.luminanceDownSamplePostProcesses.push(postProcess);
  50274. }
  50275. // Create callbacks and add effects
  50276. var lastLuminance = this.luminancePostProcess;
  50277. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  50278. var downSampleOffsets = new Array(18);
  50279. pp.onApply = function (effect) {
  50280. var id = 0;
  50281. for (var x = -1; x < 2; x++) {
  50282. for (var y = -1; y < 2; y++) {
  50283. downSampleOffsets[id] = x / lastLuminance.width;
  50284. downSampleOffsets[id + 1] = y / lastLuminance.height;
  50285. id += 2;
  50286. }
  50287. }
  50288. effect.setArray2("dsOffsets", downSampleOffsets);
  50289. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  50290. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50291. lastLuminance = _this.luminancePostProcess;
  50292. }
  50293. else {
  50294. lastLuminance = pp;
  50295. }
  50296. };
  50297. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  50298. pp.onAfterRender = function (effect) {
  50299. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  50300. 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);
  50301. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  50302. };
  50303. }
  50304. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  50305. });
  50306. };
  50307. // Create HDR post-process
  50308. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  50309. var _this = this;
  50310. 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);
  50311. var outputLiminance = 1;
  50312. var time = 0;
  50313. var lastTime = 0;
  50314. this.hdrPostProcess.onApply = function (effect) {
  50315. effect.setTextureFromPostProcess("textureAdderSampler", _this._bloomEnabled ? _this._currentHDRSource : _this.originalPostProcess);
  50316. time += scene.getEngine().getDeltaTime();
  50317. if (outputLiminance < 0) {
  50318. outputLiminance = _this._hdrCurrentLuminance;
  50319. }
  50320. else {
  50321. var dt = (lastTime - time) / 1000.0;
  50322. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  50323. outputLiminance += _this.hdrDecreaseRate * dt;
  50324. }
  50325. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  50326. outputLiminance -= _this.hdrIncreaseRate * dt;
  50327. }
  50328. else {
  50329. outputLiminance = _this._hdrCurrentLuminance;
  50330. }
  50331. }
  50332. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  50333. effect.setFloat("averageLuminance", outputLiminance);
  50334. lastTime = time;
  50335. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  50336. };
  50337. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  50338. };
  50339. // Create lens flare post-process
  50340. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  50341. var _this = this;
  50342. 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);
  50343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  50344. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  50345. 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);
  50346. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  50347. var resolution = new BABYLON.Vector2(0, 0);
  50348. // Lens flare
  50349. this.lensFlarePostProcess.onApply = function (effect) {
  50350. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.gaussianBlurHPostProcesses[0] : _this.originalPostProcess);
  50351. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  50352. effect.setFloat("strength", _this.lensFlareStrength);
  50353. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  50354. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  50355. // Shift
  50356. resolution.x = _this.lensFlarePostProcess.width;
  50357. resolution.y = _this.lensFlarePostProcess.height;
  50358. effect.setVector2("resolution", resolution);
  50359. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  50360. };
  50361. // Compose
  50362. 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);
  50363. 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);
  50364. this.lensFlareComposePostProcess.onApply = function (effect) {
  50365. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  50366. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  50367. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  50368. // Lens start rotation matrix
  50369. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  50370. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  50371. 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));
  50372. camRot *= 4.0;
  50373. 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);
  50374. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  50375. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  50376. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  50377. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  50378. };
  50379. };
  50380. // Create depth-of-field post-process
  50381. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  50382. var _this = this;
  50383. 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);
  50384. this.depthOfFieldPostProcess.onApply = function (effect) {
  50385. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  50386. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  50387. effect.setFloat("distance", _this.depthOfFieldDistance);
  50388. };
  50389. // Add to pipeline
  50390. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  50391. };
  50392. // Create motion blur post-process
  50393. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  50394. var _this = this;
  50395. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  50396. var motionScale = 0;
  50397. var prevViewProjection = BABYLON.Matrix.Identity();
  50398. var invViewProjection = BABYLON.Matrix.Identity();
  50399. var viewProjection = BABYLON.Matrix.Identity();
  50400. var screenSize = BABYLON.Vector2.Zero();
  50401. this.motionBlurPostProcess.onApply = function (effect) {
  50402. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  50403. viewProjection.invertToRef(invViewProjection);
  50404. effect.setMatrix("inverseViewProjection", invViewProjection);
  50405. effect.setMatrix("prevViewProjection", prevViewProjection);
  50406. prevViewProjection = viewProjection;
  50407. screenSize.x = _this.motionBlurPostProcess.width;
  50408. screenSize.y = _this.motionBlurPostProcess.height;
  50409. effect.setVector2("screenSize", screenSize);
  50410. motionScale = scene.getEngine().getFps() / 60.0;
  50411. effect.setFloat("motionScale", motionScale);
  50412. effect.setFloat("motionStrength", _this.motionStrength);
  50413. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  50414. };
  50415. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  50416. };
  50417. // Dispose
  50418. StandardRenderingPipeline.prototype.dispose = function () {
  50419. for (var i = 0; i < this._cameras.length; i++) {
  50420. var camera = this._cameras[i];
  50421. this.originalPostProcess.dispose(camera);
  50422. this.downSampleX4PostProcess.dispose(camera);
  50423. this.brightPassPostProcess.dispose(camera);
  50424. this.textureAdderPostProcess.dispose(camera);
  50425. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  50426. this.gaussianBlurHPostProcesses[j].dispose(camera);
  50427. }
  50428. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  50429. this.gaussianBlurVPostProcesses[j].dispose(camera);
  50430. }
  50431. this.textureAdderFinalPostProcess.dispose(camera);
  50432. this.lensFlarePostProcess.dispose(camera);
  50433. this.lensFlareComposePostProcess.dispose(camera);
  50434. this.depthOfFieldPostProcess.dispose(camera);
  50435. this.motionBlurPostProcess.dispose(camera);
  50436. }
  50437. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  50438. _super.prototype.dispose.call(this);
  50439. };
  50440. // Serialize rendering pipeline
  50441. StandardRenderingPipeline.prototype.serialize = function () {
  50442. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50443. serializationObject.customType = "StandardRenderingPipeline";
  50444. return serializationObject;
  50445. };
  50446. // Parse serialized pipeline
  50447. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  50448. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  50449. };
  50450. return StandardRenderingPipeline;
  50451. }(BABYLON.PostProcessRenderPipeline));
  50452. // Luminance steps
  50453. StandardRenderingPipeline.LuminanceSteps = 6;
  50454. __decorate([
  50455. BABYLON.serialize()
  50456. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  50457. __decorate([
  50458. BABYLON.serialize()
  50459. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  50460. __decorate([
  50461. BABYLON.serialize()
  50462. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  50463. __decorate([
  50464. BABYLON.serialize()
  50465. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  50466. __decorate([
  50467. BABYLON.serialize()
  50468. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  50469. __decorate([
  50470. BABYLON.serialize()
  50471. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  50472. __decorate([
  50473. BABYLON.serialize()
  50474. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  50475. __decorate([
  50476. BABYLON.serializeAsTexture("lensTexture")
  50477. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  50478. __decorate([
  50479. BABYLON.serialize()
  50480. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  50481. __decorate([
  50482. BABYLON.serialize()
  50483. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  50484. __decorate([
  50485. BABYLON.serialize()
  50486. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  50487. __decorate([
  50488. BABYLON.serializeAsTexture("lensColorTexture")
  50489. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  50490. __decorate([
  50491. BABYLON.serialize()
  50492. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  50493. __decorate([
  50494. BABYLON.serialize()
  50495. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  50496. __decorate([
  50497. BABYLON.serialize()
  50498. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  50499. __decorate([
  50500. BABYLON.serialize()
  50501. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  50502. __decorate([
  50503. BABYLON.serializeAsTexture("lensStarTexture")
  50504. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  50505. __decorate([
  50506. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  50507. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  50508. __decorate([
  50509. BABYLON.serialize()
  50510. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  50511. __decorate([
  50512. BABYLON.serialize()
  50513. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  50514. __decorate([
  50515. BABYLON.serialize()
  50516. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  50517. __decorate([
  50518. BABYLON.serialize()
  50519. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  50520. __decorate([
  50521. BABYLON.serialize()
  50522. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  50523. __decorate([
  50524. BABYLON.serialize()
  50525. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  50526. __decorate([
  50527. BABYLON.serialize()
  50528. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  50529. __decorate([
  50530. BABYLON.serialize()
  50531. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  50532. __decorate([
  50533. BABYLON.serialize()
  50534. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  50535. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  50536. })(BABYLON || (BABYLON = {}));
  50537. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  50538. var BABYLON;
  50539. (function (BABYLON) {
  50540. var FxaaPostProcess = (function (_super) {
  50541. __extends(FxaaPostProcess, _super);
  50542. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  50543. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50544. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  50545. _this.onApplyObservable.add(function (effect) {
  50546. var texelSize = _this.texelSize;
  50547. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  50548. });
  50549. return _this;
  50550. }
  50551. return FxaaPostProcess;
  50552. }(BABYLON.PostProcess));
  50553. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50554. })(BABYLON || (BABYLON = {}));
  50555. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50556. var BABYLON;
  50557. (function (BABYLON) {
  50558. var DefaultRenderingPipeline = (function (_super) {
  50559. __extends(DefaultRenderingPipeline, _super);
  50560. /**
  50561. * @constructor
  50562. * @param {string} name - The rendering pipeline name
  50563. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  50564. * @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)
  50565. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  50566. */
  50567. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  50568. var _this = _super.call(this, scene.getEngine(), name) || this;
  50569. _this.PassPostProcessId = "PassPostProcessEffect";
  50570. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  50571. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  50572. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  50573. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  50574. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  50575. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  50576. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  50577. // IAnimatable
  50578. _this.animations = [];
  50579. // Values
  50580. _this._bloomEnabled = false;
  50581. _this._fxaaEnabled = false;
  50582. _this._imageProcessingEnabled = true;
  50583. _this._bloomScale = 0.6;
  50584. /**
  50585. * Specifies the size of the bloom blur kernel, relative to the final output size
  50586. */
  50587. _this.bloomKernel = 64;
  50588. /**
  50589. * Specifies the weight of the bloom in the final rendering
  50590. */
  50591. _this._bloomWeight = 0.15;
  50592. _this._cameras = cameras || [];
  50593. // Initialize
  50594. _this._hdr = hdr;
  50595. _this._scene = scene;
  50596. // Misc
  50597. _this._defaultPipelineTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50598. // Attach
  50599. scene.postProcessRenderPipelineManager.addPipeline(_this);
  50600. _this._buildPipeline();
  50601. return _this;
  50602. }
  50603. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  50604. get: function () {
  50605. return this._bloomWeight;
  50606. },
  50607. set: function (value) {
  50608. if (this._bloomWeight === value) {
  50609. return;
  50610. }
  50611. this._bloomWeight = value;
  50612. if (this._hdr && this.copyBack) {
  50613. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  50614. }
  50615. },
  50616. enumerable: true,
  50617. configurable: true
  50618. });
  50619. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  50620. get: function () {
  50621. return this._bloomScale;
  50622. },
  50623. set: function (value) {
  50624. if (this._bloomScale === value) {
  50625. return;
  50626. }
  50627. this._bloomScale = value;
  50628. this._buildPipeline();
  50629. },
  50630. enumerable: true,
  50631. configurable: true
  50632. });
  50633. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  50634. get: function () {
  50635. return this._bloomEnabled;
  50636. },
  50637. set: function (enabled) {
  50638. if (this._bloomEnabled === enabled) {
  50639. return;
  50640. }
  50641. this._bloomEnabled = enabled;
  50642. this._buildPipeline();
  50643. },
  50644. enumerable: true,
  50645. configurable: true
  50646. });
  50647. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  50648. get: function () {
  50649. return this._fxaaEnabled;
  50650. },
  50651. set: function (enabled) {
  50652. if (this._fxaaEnabled === enabled) {
  50653. return;
  50654. }
  50655. this._fxaaEnabled = enabled;
  50656. this._buildPipeline();
  50657. },
  50658. enumerable: true,
  50659. configurable: true
  50660. });
  50661. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  50662. get: function () {
  50663. return this._imageProcessingEnabled;
  50664. },
  50665. set: function (enabled) {
  50666. if (this._imageProcessingEnabled === enabled) {
  50667. return;
  50668. }
  50669. this._imageProcessingEnabled = enabled;
  50670. this._buildPipeline();
  50671. },
  50672. enumerable: true,
  50673. configurable: true
  50674. });
  50675. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  50676. var _this = this;
  50677. var engine = this._scene.getEngine();
  50678. this._disposePostProcesses();
  50679. this._reset();
  50680. if (this.bloomEnabled) {
  50681. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50682. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  50683. if (!this._hdr) {
  50684. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50685. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  50686. this.highlights.autoClear = false;
  50687. this.highlights.alwaysForcePOT = true;
  50688. }
  50689. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50690. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  50691. this.blurX.alwaysForcePOT = true;
  50692. this.blurX.autoClear = false;
  50693. this.blurX.onActivateObservable.add(function () {
  50694. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  50695. _this.blurX.kernel = _this.bloomKernel * dw;
  50696. });
  50697. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50698. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  50699. this.blurY.alwaysForcePOT = true;
  50700. this.blurY.autoClear = false;
  50701. this.blurY.onActivateObservable.add(function () {
  50702. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  50703. _this.blurY.kernel = _this.bloomKernel * dh;
  50704. });
  50705. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50706. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  50707. this.copyBack.alwaysForcePOT = true;
  50708. if (this._hdr) {
  50709. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  50710. var w = this.bloomWeight;
  50711. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  50712. }
  50713. else {
  50714. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  50715. }
  50716. this.copyBack.autoClear = false;
  50717. }
  50718. if (this._imageProcessingEnabled) {
  50719. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50720. if (this._hdr) {
  50721. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  50722. }
  50723. }
  50724. if (this.fxaaEnabled) {
  50725. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50726. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  50727. this.fxaa.autoClear = !this.bloomEnabled && !this.imageProcessing;
  50728. }
  50729. else {
  50730. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  50731. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  50732. this.finalMerge.autoClear = !this.bloomEnabled && !this.imageProcessing;
  50733. }
  50734. if (this.bloomEnabled) {
  50735. if (this._hdr) {
  50736. this.copyBack.shareOutputWith(this.blurX);
  50737. if (this.imageProcessing) {
  50738. this.imageProcessing.shareOutputWith(this.pass);
  50739. this.imageProcessing.autoClear = false;
  50740. }
  50741. else if (this.fxaa) {
  50742. this.fxaa.shareOutputWith(this.pass);
  50743. }
  50744. else {
  50745. this.finalMerge.shareOutputWith(this.pass);
  50746. }
  50747. }
  50748. else {
  50749. if (this.fxaa) {
  50750. this.fxaa.shareOutputWith(this.pass);
  50751. }
  50752. else {
  50753. this.finalMerge.shareOutputWith(this.pass);
  50754. }
  50755. }
  50756. }
  50757. if (this._cameras !== null) {
  50758. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  50759. }
  50760. };
  50761. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  50762. for (var i = 0; i < this._cameras.length; i++) {
  50763. var camera = this._cameras[i];
  50764. if (this.pass) {
  50765. this.pass.dispose(camera);
  50766. this.pass = null;
  50767. }
  50768. if (this.highlights) {
  50769. this.highlights.dispose(camera);
  50770. this.highlights = null;
  50771. }
  50772. if (this.blurX) {
  50773. this.blurX.dispose(camera);
  50774. this.blurX = null;
  50775. }
  50776. if (this.blurY) {
  50777. this.blurY.dispose(camera);
  50778. this.blurY = null;
  50779. }
  50780. if (this.copyBack) {
  50781. this.copyBack.dispose(camera);
  50782. this.copyBack = null;
  50783. }
  50784. if (this.imageProcessing) {
  50785. this.imageProcessing.dispose(camera);
  50786. this.imageProcessing = null;
  50787. }
  50788. if (this.fxaa) {
  50789. this.fxaa.dispose(camera);
  50790. this.fxaa = null;
  50791. }
  50792. if (this.finalMerge) {
  50793. this.finalMerge.dispose(camera);
  50794. this.finalMerge = null;
  50795. }
  50796. }
  50797. };
  50798. // Dispose
  50799. DefaultRenderingPipeline.prototype.dispose = function () {
  50800. this._disposePostProcesses();
  50801. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  50802. _super.prototype.dispose.call(this);
  50803. };
  50804. // Serialize rendering pipeline
  50805. DefaultRenderingPipeline.prototype.serialize = function () {
  50806. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50807. serializationObject.customType = "DefaultRenderingPipeline";
  50808. return serializationObject;
  50809. };
  50810. // Parse serialized pipeline
  50811. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  50812. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  50813. };
  50814. return DefaultRenderingPipeline;
  50815. }(BABYLON.PostProcessRenderPipeline));
  50816. __decorate([
  50817. BABYLON.serialize()
  50818. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  50819. __decorate([
  50820. BABYLON.serialize()
  50821. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  50822. __decorate([
  50823. BABYLON.serialize()
  50824. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  50825. __decorate([
  50826. BABYLON.serialize()
  50827. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  50828. __decorate([
  50829. BABYLON.serialize()
  50830. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  50831. __decorate([
  50832. BABYLON.serialize()
  50833. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  50834. __decorate([
  50835. BABYLON.serialize()
  50836. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  50837. __decorate([
  50838. BABYLON.serialize()
  50839. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  50840. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  50841. })(BABYLON || (BABYLON = {}));
  50842. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  50843. var BABYLON;
  50844. (function (BABYLON) {
  50845. var GeometryBufferRenderer = (function () {
  50846. function GeometryBufferRenderer(scene, ratio) {
  50847. if (ratio === void 0) { ratio = 1; }
  50848. var _this = this;
  50849. this._viewMatrix = BABYLON.Matrix.Zero();
  50850. this._projectionMatrix = BABYLON.Matrix.Zero();
  50851. this._transformMatrix = BABYLON.Matrix.Zero();
  50852. this._worldViewProjection = BABYLON.Matrix.Zero();
  50853. this._scene = scene;
  50854. var engine = scene.getEngine();
  50855. // Render target
  50856. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, 2, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  50857. if (!this.isSupported) {
  50858. return null;
  50859. }
  50860. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50861. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50862. this._multiRenderTarget.refreshRate = 1;
  50863. this._multiRenderTarget.renderParticles = false;
  50864. this._multiRenderTarget.renderList = null;
  50865. // set default depth value to 1.0 (far away)
  50866. this._multiRenderTarget.onClearObservable.add(function (engine) {
  50867. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  50868. });
  50869. // Custom render function
  50870. var renderSubMesh = function (subMesh) {
  50871. var mesh = subMesh.getRenderingMesh();
  50872. var scene = _this._scene;
  50873. var engine = scene.getEngine();
  50874. // Culling
  50875. engine.setState(subMesh.getMaterial().backFaceCulling);
  50876. // Managing instances
  50877. var batch = mesh._getInstancesRenderList(subMesh._id);
  50878. if (batch.mustReturn) {
  50879. return;
  50880. }
  50881. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  50882. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  50883. engine.enableEffect(_this._effect);
  50884. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  50885. var material = subMesh.getMaterial();
  50886. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  50887. _this._effect.setMatrix("view", scene.getViewMatrix());
  50888. // Alpha test
  50889. if (material && material.needAlphaTesting()) {
  50890. var alphaTexture = material.getAlphaTestTexture();
  50891. _this._effect.setTexture("diffuseSampler", alphaTexture);
  50892. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  50893. }
  50894. // Bones
  50895. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50896. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  50897. }
  50898. // Draw
  50899. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  50900. }
  50901. };
  50902. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  50903. var index;
  50904. for (index = 0; index < opaqueSubMeshes.length; index++) {
  50905. renderSubMesh(opaqueSubMeshes.data[index]);
  50906. }
  50907. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  50908. renderSubMesh(alphaTestSubMeshes.data[index]);
  50909. }
  50910. };
  50911. }
  50912. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  50913. set: function (meshes) {
  50914. this._multiRenderTarget.renderList = meshes;
  50915. },
  50916. enumerable: true,
  50917. configurable: true
  50918. });
  50919. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  50920. get: function () {
  50921. return this._multiRenderTarget.isSupported;
  50922. },
  50923. enumerable: true,
  50924. configurable: true
  50925. });
  50926. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  50927. var material = subMesh.getMaterial();
  50928. if (material && material.disableDepthWrite) {
  50929. return false;
  50930. }
  50931. var defines = [];
  50932. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  50933. var mesh = subMesh.getMesh();
  50934. var scene = mesh.getScene();
  50935. // Alpha test
  50936. if (material && material.needAlphaTesting()) {
  50937. defines.push("#define ALPHATEST");
  50938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50939. attribs.push(BABYLON.VertexBuffer.UVKind);
  50940. defines.push("#define UV1");
  50941. }
  50942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  50943. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  50944. defines.push("#define UV2");
  50945. }
  50946. }
  50947. // Bones
  50948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  50949. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50950. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50951. if (mesh.numBoneInfluencers > 4) {
  50952. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50953. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50954. }
  50955. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50956. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50957. }
  50958. else {
  50959. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50960. }
  50961. // Instances
  50962. if (useInstances) {
  50963. defines.push("#define INSTANCES");
  50964. attribs.push("world0");
  50965. attribs.push("world1");
  50966. attribs.push("world2");
  50967. attribs.push("world3");
  50968. }
  50969. // Get correct effect
  50970. var join = defines.join("\n");
  50971. if (this._cachedDefines !== join) {
  50972. this._cachedDefines = join;
  50973. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  50974. }
  50975. return this._effect.isReady();
  50976. };
  50977. GeometryBufferRenderer.prototype.getGBuffer = function () {
  50978. return this._multiRenderTarget;
  50979. };
  50980. // Methods
  50981. GeometryBufferRenderer.prototype.dispose = function () {
  50982. this.getGBuffer().dispose();
  50983. };
  50984. return GeometryBufferRenderer;
  50985. }());
  50986. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  50987. })(BABYLON || (BABYLON = {}));
  50988. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  50989. var BABYLON;
  50990. (function (BABYLON) {
  50991. var RefractionPostProcess = (function (_super) {
  50992. __extends(RefractionPostProcess, _super);
  50993. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50994. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50995. _this.color = color;
  50996. _this.depth = depth;
  50997. _this.colorLevel = colorLevel;
  50998. _this.onActivateObservable.add(function (cam) {
  50999. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  51000. });
  51001. _this.onApplyObservable.add(function (effect) {
  51002. effect.setColor3("baseColor", _this.color);
  51003. effect.setFloat("depth", _this.depth);
  51004. effect.setFloat("colorLevel", _this.colorLevel);
  51005. effect.setTexture("refractionSampler", _this._refRexture);
  51006. });
  51007. return _this;
  51008. }
  51009. // Methods
  51010. RefractionPostProcess.prototype.dispose = function (camera) {
  51011. if (this._refRexture) {
  51012. this._refRexture.dispose();
  51013. }
  51014. _super.prototype.dispose.call(this, camera);
  51015. };
  51016. return RefractionPostProcess;
  51017. }(BABYLON.PostProcess));
  51018. BABYLON.RefractionPostProcess = RefractionPostProcess;
  51019. })(BABYLON || (BABYLON = {}));
  51020. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  51021. var BABYLON;
  51022. (function (BABYLON) {
  51023. var BlackAndWhitePostProcess = (function (_super) {
  51024. __extends(BlackAndWhitePostProcess, _super);
  51025. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  51026. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  51027. _this.degree = 1;
  51028. _this.onApplyObservable.add(function (effect) {
  51029. effect.setFloat("degree", _this.degree);
  51030. });
  51031. return _this;
  51032. }
  51033. return BlackAndWhitePostProcess;
  51034. }(BABYLON.PostProcess));
  51035. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  51036. })(BABYLON || (BABYLON = {}));
  51037. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  51038. var BABYLON;
  51039. (function (BABYLON) {
  51040. var ConvolutionPostProcess = (function (_super) {
  51041. __extends(ConvolutionPostProcess, _super);
  51042. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  51043. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  51044. _this.kernel = kernel;
  51045. _this.onApply = function (effect) {
  51046. effect.setFloat2("screenSize", _this.width, _this.height);
  51047. effect.setArray("kernel", _this.kernel);
  51048. };
  51049. return _this;
  51050. }
  51051. return ConvolutionPostProcess;
  51052. }(BABYLON.PostProcess));
  51053. // Statics
  51054. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  51055. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  51056. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  51057. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  51058. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  51059. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  51060. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  51061. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  51062. })(BABYLON || (BABYLON = {}));
  51063. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  51064. var BABYLON;
  51065. (function (BABYLON) {
  51066. var FilterPostProcess = (function (_super) {
  51067. __extends(FilterPostProcess, _super);
  51068. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  51069. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  51070. _this.kernelMatrix = kernelMatrix;
  51071. _this.onApply = function (effect) {
  51072. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  51073. };
  51074. return _this;
  51075. }
  51076. return FilterPostProcess;
  51077. }(BABYLON.PostProcess));
  51078. BABYLON.FilterPostProcess = FilterPostProcess;
  51079. })(BABYLON || (BABYLON = {}));
  51080. //# sourceMappingURL=babylon.filterPostProcess.js.map
  51081. var BABYLON;
  51082. (function (BABYLON) {
  51083. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51084. var VolumetricLightScatteringPostProcess = (function (_super) {
  51085. __extends(VolumetricLightScatteringPostProcess, _super);
  51086. /**
  51087. * @constructor
  51088. * @param {string} name - The post-process name
  51089. * @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)
  51090. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51091. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51092. * @param {number} samples - The post-process quality, default 100
  51093. * @param {number} samplingMode - The post-process filtering mode
  51094. * @param {BABYLON.Engine} engine - The babylon engine
  51095. * @param {boolean} reusable - If the post-process is reusable
  51096. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51097. */
  51098. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51099. if (samples === void 0) { samples = 100; }
  51100. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51101. 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;
  51102. _this._screenCoordinates = BABYLON.Vector2.Zero();
  51103. /**
  51104. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51105. * @type {Vector3}
  51106. */
  51107. _this.customMeshPosition = BABYLON.Vector3.Zero();
  51108. /**
  51109. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51110. * @type {boolean}
  51111. */
  51112. _this.useCustomMeshPosition = false;
  51113. /**
  51114. * If the post-process should inverse the light scattering direction
  51115. * @type {boolean}
  51116. */
  51117. _this.invert = true;
  51118. /**
  51119. * Array containing the excluded meshes not rendered in the internal pass
  51120. */
  51121. _this.excludedMeshes = new Array();
  51122. /**
  51123. * Controls the overall intensity of the post-process
  51124. * @type {number}
  51125. */
  51126. _this.exposure = 0.3;
  51127. /**
  51128. * Dissipates each sample's contribution in range [0, 1]
  51129. * @type {number}
  51130. */
  51131. _this.decay = 0.96815;
  51132. /**
  51133. * Controls the overall intensity of each sample
  51134. * @type {number}
  51135. */
  51136. _this.weight = 0.58767;
  51137. /**
  51138. * Controls the density of each sample
  51139. * @type {number}
  51140. */
  51141. _this.density = 0.926;
  51142. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51143. var engine = scene.getEngine();
  51144. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51145. // Configure mesh
  51146. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51147. // Configure
  51148. _this._createPass(scene, ratio.passRatio || ratio);
  51149. _this.onActivate = function (camera) {
  51150. if (!_this.isSupported) {
  51151. _this.dispose(camera);
  51152. }
  51153. _this.onActivate = null;
  51154. };
  51155. _this.onApplyObservable.add(function (effect) {
  51156. _this._updateMeshScreenCoordinates(scene);
  51157. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51158. effect.setFloat("exposure", _this.exposure);
  51159. effect.setFloat("decay", _this.decay);
  51160. effect.setFloat("weight", _this.weight);
  51161. effect.setFloat("density", _this.density);
  51162. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51163. });
  51164. return _this;
  51165. }
  51166. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51167. get: function () {
  51168. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51169. return false;
  51170. },
  51171. set: function (useDiffuseColor) {
  51172. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51173. },
  51174. enumerable: true,
  51175. configurable: true
  51176. });
  51177. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51178. var mesh = subMesh.getMesh();
  51179. // Render this.mesh as default
  51180. if (mesh === this.mesh) {
  51181. return mesh.material.isReady(mesh);
  51182. }
  51183. var defines = [];
  51184. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51185. var material = subMesh.getMaterial();
  51186. var needUV = false;
  51187. // Alpha test
  51188. if (material) {
  51189. if (material.needAlphaTesting()) {
  51190. defines.push("#define ALPHATEST");
  51191. }
  51192. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51193. attribs.push(BABYLON.VertexBuffer.UVKind);
  51194. defines.push("#define UV1");
  51195. }
  51196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51197. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51198. defines.push("#define UV2");
  51199. }
  51200. }
  51201. // Bones
  51202. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51203. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51204. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51205. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51206. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51207. }
  51208. else {
  51209. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51210. }
  51211. // Instances
  51212. if (useInstances) {
  51213. defines.push("#define INSTANCES");
  51214. attribs.push("world0");
  51215. attribs.push("world1");
  51216. attribs.push("world2");
  51217. attribs.push("world3");
  51218. }
  51219. // Get correct effect
  51220. var join = defines.join("\n");
  51221. if (this._cachedDefines !== join) {
  51222. this._cachedDefines = join;
  51223. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  51224. }
  51225. return this._volumetricLightScatteringPass.isReady();
  51226. };
  51227. /**
  51228. * Sets the new light position for light scattering effect
  51229. * @param {BABYLON.Vector3} The new custom light position
  51230. */
  51231. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  51232. this.customMeshPosition = position;
  51233. };
  51234. /**
  51235. * Returns the light position for light scattering effect
  51236. * @return {BABYLON.Vector3} The custom light position
  51237. */
  51238. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  51239. return this.customMeshPosition;
  51240. };
  51241. /**
  51242. * Disposes the internal assets and detaches the post-process from the camera
  51243. */
  51244. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  51245. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  51246. if (rttIndex !== -1) {
  51247. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  51248. }
  51249. this._volumetricLightScatteringRTT.dispose();
  51250. _super.prototype.dispose.call(this, camera);
  51251. };
  51252. /**
  51253. * Returns the render target texture used by the post-process
  51254. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  51255. */
  51256. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  51257. return this._volumetricLightScatteringRTT;
  51258. };
  51259. // Private methods
  51260. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  51261. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  51262. return true;
  51263. }
  51264. return false;
  51265. };
  51266. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  51267. var _this = this;
  51268. var engine = scene.getEngine();
  51269. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  51270. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51271. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51272. this._volumetricLightScatteringRTT.renderList = null;
  51273. this._volumetricLightScatteringRTT.renderParticles = false;
  51274. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  51275. // Custom render function for submeshes
  51276. var renderSubMesh = function (subMesh) {
  51277. var mesh = subMesh.getRenderingMesh();
  51278. if (_this._meshExcluded(mesh)) {
  51279. return;
  51280. }
  51281. var scene = mesh.getScene();
  51282. var engine = scene.getEngine();
  51283. // Culling
  51284. engine.setState(subMesh.getMaterial().backFaceCulling);
  51285. // Managing instances
  51286. var batch = mesh._getInstancesRenderList(subMesh._id);
  51287. if (batch.mustReturn) {
  51288. return;
  51289. }
  51290. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51291. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51292. var effect = _this._volumetricLightScatteringPass;
  51293. if (mesh === _this.mesh) {
  51294. if (subMesh.effect) {
  51295. effect = subMesh.effect;
  51296. }
  51297. else {
  51298. effect = subMesh.getMaterial().getEffect();
  51299. }
  51300. }
  51301. engine.enableEffect(effect);
  51302. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  51303. if (mesh === _this.mesh) {
  51304. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  51305. }
  51306. else {
  51307. var material = subMesh.getMaterial();
  51308. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  51309. // Alpha test
  51310. if (material && material.needAlphaTesting()) {
  51311. var alphaTexture = material.getAlphaTestTexture();
  51312. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  51313. if (alphaTexture) {
  51314. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51315. }
  51316. }
  51317. // Bones
  51318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51319. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51320. }
  51321. }
  51322. // Draw
  51323. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  51324. }
  51325. };
  51326. // Render target texture callbacks
  51327. var savedSceneClearColor;
  51328. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  51329. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  51330. savedSceneClearColor = scene.clearColor;
  51331. scene.clearColor = sceneClearColor;
  51332. });
  51333. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  51334. scene.clearColor = savedSceneClearColor;
  51335. });
  51336. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  51337. var engine = scene.getEngine();
  51338. var index;
  51339. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51340. renderSubMesh(opaqueSubMeshes.data[index]);
  51341. }
  51342. engine.setAlphaTesting(true);
  51343. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51344. renderSubMesh(alphaTestSubMeshes.data[index]);
  51345. }
  51346. engine.setAlphaTesting(false);
  51347. if (transparentSubMeshes.length) {
  51348. // Sort sub meshes
  51349. for (index = 0; index < transparentSubMeshes.length; index++) {
  51350. var submesh = transparentSubMeshes.data[index];
  51351. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  51352. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  51353. }
  51354. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  51355. sortedArray.sort(function (a, b) {
  51356. // Alpha index first
  51357. if (a._alphaIndex > b._alphaIndex) {
  51358. return 1;
  51359. }
  51360. if (a._alphaIndex < b._alphaIndex) {
  51361. return -1;
  51362. }
  51363. // Then distance to camera
  51364. if (a._distanceToCamera < b._distanceToCamera) {
  51365. return 1;
  51366. }
  51367. if (a._distanceToCamera > b._distanceToCamera) {
  51368. return -1;
  51369. }
  51370. return 0;
  51371. });
  51372. // Render sub meshes
  51373. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51374. for (index = 0; index < sortedArray.length; index++) {
  51375. renderSubMesh(sortedArray[index]);
  51376. }
  51377. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51378. }
  51379. };
  51380. };
  51381. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  51382. var transform = scene.getTransformMatrix();
  51383. var meshPosition;
  51384. if (this.useCustomMeshPosition) {
  51385. meshPosition = this.customMeshPosition;
  51386. }
  51387. else if (this.attachedNode) {
  51388. meshPosition = this.attachedNode.position;
  51389. }
  51390. else {
  51391. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  51392. }
  51393. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  51394. this._screenCoordinates.x = pos.x / this._viewPort.width;
  51395. this._screenCoordinates.y = pos.y / this._viewPort.height;
  51396. if (this.invert)
  51397. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  51398. };
  51399. // Static methods
  51400. /**
  51401. * Creates a default mesh for the Volumeric Light Scattering post-process
  51402. * @param {string} The mesh name
  51403. * @param {BABYLON.Scene} The scene where to create the mesh
  51404. * @return {BABYLON.Mesh} the default mesh
  51405. */
  51406. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  51407. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  51408. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  51409. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  51410. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  51411. mesh.material = material;
  51412. return mesh;
  51413. };
  51414. return VolumetricLightScatteringPostProcess;
  51415. }(BABYLON.PostProcess));
  51416. __decorate([
  51417. BABYLON.serializeAsVector3()
  51418. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  51419. __decorate([
  51420. BABYLON.serialize()
  51421. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  51422. __decorate([
  51423. BABYLON.serialize()
  51424. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  51425. __decorate([
  51426. BABYLON.serializeAsMeshReference()
  51427. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  51428. __decorate([
  51429. BABYLON.serialize()
  51430. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  51431. __decorate([
  51432. BABYLON.serialize()
  51433. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  51434. __decorate([
  51435. BABYLON.serialize()
  51436. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  51437. __decorate([
  51438. BABYLON.serialize()
  51439. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  51440. __decorate([
  51441. BABYLON.serialize()
  51442. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  51443. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  51444. })(BABYLON || (BABYLON = {}));
  51445. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  51446. //
  51447. // This post-process allows the modification of rendered colors by using
  51448. // a 'look-up table' (LUT). This effect is also called Color Grading.
  51449. //
  51450. // The object needs to be provided an url to a texture containing the color
  51451. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  51452. // Use an image editing software to tweak the LUT to match your needs.
  51453. //
  51454. // For an example of a color LUT, see here:
  51455. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  51456. // For explanations on color grading, see here:
  51457. // http://udn.epicgames.com/Three/ColorGrading.html
  51458. //
  51459. var BABYLON;
  51460. (function (BABYLON) {
  51461. var ColorCorrectionPostProcess = (function (_super) {
  51462. __extends(ColorCorrectionPostProcess, _super);
  51463. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  51464. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  51465. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51466. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  51467. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51468. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51469. _this.onApply = function (effect) {
  51470. effect.setTexture("colorTable", _this._colorTableTexture);
  51471. };
  51472. return _this;
  51473. }
  51474. return ColorCorrectionPostProcess;
  51475. }(BABYLON.PostProcess));
  51476. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  51477. })(BABYLON || (BABYLON = {}));
  51478. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  51479. var BABYLON;
  51480. (function (BABYLON) {
  51481. var TonemappingOperator;
  51482. (function (TonemappingOperator) {
  51483. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  51484. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  51485. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  51486. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  51487. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  51488. ;
  51489. var TonemapPostProcess = (function (_super) {
  51490. __extends(TonemapPostProcess, _super);
  51491. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  51492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51493. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51494. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  51495. _this._operator = _operator;
  51496. _this.exposureAdjustment = exposureAdjustment;
  51497. var defines = "#define ";
  51498. if (_this._operator === TonemappingOperator.Hable)
  51499. defines += "HABLE_TONEMAPPING";
  51500. else if (_this._operator === TonemappingOperator.Reinhard)
  51501. defines += "REINHARD_TONEMAPPING";
  51502. else if (_this._operator === TonemappingOperator.HejiDawson)
  51503. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  51504. else if (_this._operator === TonemappingOperator.Photographic)
  51505. defines += "PHOTOGRAPHIC_TONEMAPPING";
  51506. //sadly a second call to create the effect.
  51507. _this.updateEffect(defines);
  51508. _this.onApply = function (effect) {
  51509. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  51510. };
  51511. return _this;
  51512. }
  51513. return TonemapPostProcess;
  51514. }(BABYLON.PostProcess));
  51515. BABYLON.TonemapPostProcess = TonemapPostProcess;
  51516. })(BABYLON || (BABYLON = {}));
  51517. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  51518. var BABYLON;
  51519. (function (BABYLON) {
  51520. var DisplayPassPostProcess = (function (_super) {
  51521. __extends(DisplayPassPostProcess, _super);
  51522. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  51523. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  51524. }
  51525. return DisplayPassPostProcess;
  51526. }(BABYLON.PostProcess));
  51527. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  51528. })(BABYLON || (BABYLON = {}));
  51529. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  51530. var BABYLON;
  51531. (function (BABYLON) {
  51532. var HighlightsPostProcess = (function (_super) {
  51533. __extends(HighlightsPostProcess, _super);
  51534. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51535. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51536. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  51537. }
  51538. return HighlightsPostProcess;
  51539. }(BABYLON.PostProcess));
  51540. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  51541. })(BABYLON || (BABYLON = {}));
  51542. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  51543. var BABYLON;
  51544. (function (BABYLON) {
  51545. var ImageProcessingPostProcess = (function (_super) {
  51546. __extends(ImageProcessingPostProcess, _super);
  51547. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51548. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51549. var _this = _super.call(this, name, "imageProcessing", [
  51550. 'contrast',
  51551. 'vignetteSettings1',
  51552. 'vignetteSettings2',
  51553. 'cameraExposureLinear',
  51554. 'vCameraColorCurveNegative',
  51555. 'vCameraColorCurveNeutral',
  51556. 'vCameraColorCurvePositive',
  51557. 'colorTransformSettings'
  51558. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  51559. _this.colorGradingWeight = 1.0;
  51560. _this.colorCurves = new BABYLON.ColorCurves();
  51561. _this._colorCurvesEnabled = true;
  51562. _this.cameraFov = 0.5;
  51563. _this.vignetteStretch = 0;
  51564. _this.vignetteCentreX = 0;
  51565. _this.vignetteCentreY = 0;
  51566. _this.vignetteWeight = 1.5;
  51567. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  51568. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  51569. _this._vignetteEnabled = true;
  51570. _this.cameraContrast = 1.0;
  51571. _this.cameraExposure = 1.68;
  51572. _this._cameraToneMappingEnabled = true;
  51573. _this._fromLinearSpace = false;
  51574. _this._updateParameters();
  51575. _this.onApply = function (effect) {
  51576. var aspectRatio = _this.aspectRatio;
  51577. // Color
  51578. if (_this._colorCurvesEnabled) {
  51579. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  51580. }
  51581. if (_this._vignetteEnabled) {
  51582. // Vignette
  51583. var vignetteScaleY = Math.tan(_this.cameraFov * 0.5);
  51584. var vignetteScaleX = vignetteScaleY * aspectRatio;
  51585. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  51586. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  51587. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  51588. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  51589. var vignettePower = -2.0 * _this.vignetteWeight;
  51590. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  51591. }
  51592. // Contrast and exposure
  51593. effect.setFloat('contrast', _this.cameraContrast);
  51594. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposure) * Math.PI);
  51595. // Color transform settings
  51596. if (_this._colorGradingTexture) {
  51597. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  51598. var textureSize = _this.colorGradingTexture.getSize().height;
  51599. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  51600. 0.5 / textureSize, // textureOffset
  51601. textureSize, // textureSize
  51602. _this.colorGradingWeight // weight
  51603. );
  51604. }
  51605. };
  51606. return _this;
  51607. }
  51608. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  51609. get: function () {
  51610. return this._colorGradingTexture;
  51611. },
  51612. set: function (value) {
  51613. if (this._colorGradingTexture === value) {
  51614. return;
  51615. }
  51616. this._colorGradingTexture = value;
  51617. this._updateParameters();
  51618. },
  51619. enumerable: true,
  51620. configurable: true
  51621. });
  51622. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  51623. get: function () {
  51624. return this._vignetteBlendMode;
  51625. },
  51626. set: function (value) {
  51627. if (this._vignetteBlendMode === value) {
  51628. return;
  51629. }
  51630. this._vignetteBlendMode = value;
  51631. this._updateParameters();
  51632. },
  51633. enumerable: true,
  51634. configurable: true
  51635. });
  51636. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  51637. get: function () {
  51638. return this._colorCurvesEnabled;
  51639. },
  51640. set: function (value) {
  51641. if (this._colorCurvesEnabled === value) {
  51642. return;
  51643. }
  51644. this._colorCurvesEnabled = value;
  51645. this._updateParameters();
  51646. },
  51647. enumerable: true,
  51648. configurable: true
  51649. });
  51650. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  51651. get: function () {
  51652. return this._vignetteEnabled;
  51653. },
  51654. set: function (value) {
  51655. if (this._vignetteEnabled === value) {
  51656. return;
  51657. }
  51658. this._vignetteEnabled = value;
  51659. this._updateParameters();
  51660. },
  51661. enumerable: true,
  51662. configurable: true
  51663. });
  51664. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  51665. get: function () {
  51666. return this._fromLinearSpace;
  51667. },
  51668. set: function (value) {
  51669. if (this._fromLinearSpace === value) {
  51670. return;
  51671. }
  51672. this._fromLinearSpace = value;
  51673. this._updateParameters();
  51674. },
  51675. enumerable: true,
  51676. configurable: true
  51677. });
  51678. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  51679. get: function () {
  51680. return this._cameraToneMappingEnabled;
  51681. },
  51682. set: function (value) {
  51683. if (this._cameraToneMappingEnabled === value) {
  51684. return;
  51685. }
  51686. this._cameraToneMappingEnabled = value;
  51687. this._updateParameters();
  51688. },
  51689. enumerable: true,
  51690. configurable: true
  51691. });
  51692. ImageProcessingPostProcess.prototype._updateParameters = function () {
  51693. var defines = "";
  51694. var samplers = ["textureSampler"];
  51695. if (this.colorGradingTexture) {
  51696. defines = "#define COLORGRADING\r\n";
  51697. samplers.push("txColorTransform");
  51698. }
  51699. if (this._vignetteEnabled) {
  51700. defines += "#define VIGNETTE\r\n";
  51701. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  51702. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  51703. }
  51704. else {
  51705. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  51706. }
  51707. }
  51708. if (this.cameraToneMappingEnabled) {
  51709. defines += "#define TONEMAPPING\r\n";
  51710. }
  51711. if (this._colorCurvesEnabled && this.colorCurves) {
  51712. defines += "#define COLORCURVES\r\n";
  51713. }
  51714. if (this._fromLinearSpace) {
  51715. defines += "#define FROMLINEARSPACE\r\n";
  51716. }
  51717. this.updateEffect(defines, null, samplers);
  51718. };
  51719. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  51720. get: function () {
  51721. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  51722. },
  51723. enumerable: true,
  51724. configurable: true
  51725. });
  51726. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  51727. get: function () {
  51728. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  51729. },
  51730. enumerable: true,
  51731. configurable: true
  51732. });
  51733. return ImageProcessingPostProcess;
  51734. }(BABYLON.PostProcess));
  51735. // Statics
  51736. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  51737. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  51738. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  51739. })(BABYLON || (BABYLON = {}));
  51740. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  51741. var BABYLON;
  51742. (function (BABYLON) {
  51743. var BlurPostProcess = (function (_super) {
  51744. __extends(BlurPostProcess, _super);
  51745. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  51746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51747. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51748. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  51749. _this.direction = direction;
  51750. _this.onApplyObservable.add(function (effect) {
  51751. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  51752. });
  51753. _this.kernel = kernel;
  51754. return _this;
  51755. }
  51756. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  51757. /**
  51758. * Gets the length in pixels of the blur sample region
  51759. */
  51760. get: function () {
  51761. return this._idealKernel;
  51762. },
  51763. /**
  51764. * Sets the length in pixels of the blur sample region
  51765. */
  51766. set: function (v) {
  51767. if (this._idealKernel === v) {
  51768. return;
  51769. }
  51770. v = Math.max(v, 1);
  51771. this._idealKernel = v;
  51772. this._kernel = this._nearestBestKernel(v);
  51773. this._updateParameters();
  51774. },
  51775. enumerable: true,
  51776. configurable: true
  51777. });
  51778. BlurPostProcess.prototype._updateParameters = function () {
  51779. // Generate sampling offsets and weights
  51780. var N = this._kernel;
  51781. var centerIndex = (N - 1) / 2;
  51782. // Generate Gaussian sampling weights over kernel
  51783. var offsets = [];
  51784. var weights = [];
  51785. var totalWeight = 0;
  51786. for (var i = 0; i < N; i++) {
  51787. var u = i / (N - 1);
  51788. var w = this._gaussianWeight(u * 2.0 - 1);
  51789. offsets[i] = (i - centerIndex);
  51790. weights[i] = w;
  51791. totalWeight += w;
  51792. }
  51793. // Normalize weights
  51794. for (var i = 0; i < weights.length; i++) {
  51795. weights[i] /= totalWeight;
  51796. }
  51797. // Optimize: combine samples to take advantage of hardware linear sampling
  51798. // Walk from left to center, combining pairs (symmetrically)
  51799. var linearSamplingWeights = [];
  51800. var linearSamplingOffsets = [];
  51801. var linearSamplingMap = [];
  51802. for (var i = 0; i <= centerIndex; i += 2) {
  51803. var j = Math.min(i + 1, Math.floor(centerIndex));
  51804. var singleCenterSample = i === j;
  51805. if (singleCenterSample) {
  51806. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51807. }
  51808. else {
  51809. var sharedCell = j === centerIndex;
  51810. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  51811. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  51812. if (offsetLinear === 0) {
  51813. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  51814. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  51815. }
  51816. else {
  51817. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  51818. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  51819. }
  51820. }
  51821. }
  51822. for (var i = 0; i < linearSamplingMap.length; i++) {
  51823. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  51824. linearSamplingWeights[i] = linearSamplingMap[i].w;
  51825. }
  51826. // Replace with optimized
  51827. offsets = linearSamplingOffsets;
  51828. weights = linearSamplingWeights;
  51829. // Generate shaders
  51830. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  51831. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  51832. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  51833. var defines = "";
  51834. for (var i = 0; i < varyingCount; i++) {
  51835. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  51836. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  51837. }
  51838. var depCount = 0;
  51839. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  51840. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  51841. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  51842. depCount++;
  51843. }
  51844. this.updateEffect(defines, null, null, {
  51845. varyingCount: varyingCount,
  51846. depCount: depCount
  51847. });
  51848. };
  51849. /**
  51850. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  51851. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  51852. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  51853. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  51854. * The gaps between physical kernels are compensated for in the weighting of the samples
  51855. * @param idealKernel Ideal blur kernel.
  51856. * @return Nearest best kernel.
  51857. */
  51858. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  51859. var v = Math.round(idealKernel);
  51860. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  51861. var k = _a[_i];
  51862. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  51863. return Math.max(k, 3);
  51864. }
  51865. }
  51866. return Math.max(v, 3);
  51867. };
  51868. /**
  51869. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  51870. * @param x The point on the Gaussian distribution to sample.
  51871. * @return the value of the Gaussian function at x.
  51872. */
  51873. BlurPostProcess.prototype._gaussianWeight = function (x) {
  51874. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  51875. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  51876. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  51877. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  51878. // truncated at around 1.3% of peak strength.
  51879. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  51880. var sigma = (1 / 3);
  51881. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  51882. var exponent = -((x * x) / (2.0 * sigma * sigma));
  51883. var weight = (1.0 / denominator) * Math.exp(exponent);
  51884. return weight;
  51885. };
  51886. /**
  51887. * Generates a string that can be used as a floating point number in GLSL.
  51888. * @param x Value to print.
  51889. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  51890. * @return GLSL float string.
  51891. */
  51892. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  51893. if (decimalFigures === void 0) { decimalFigures = 8; }
  51894. return x.toFixed(decimalFigures).replace(/0+$/, '');
  51895. };
  51896. return BlurPostProcess;
  51897. }(BABYLON.PostProcess));
  51898. BABYLON.BlurPostProcess = BlurPostProcess;
  51899. })(BABYLON || (BABYLON = {}));
  51900. //# sourceMappingURL=babylon.blurPostProcess.js.map
  51901. /// <reference path="..\babylon.node.ts" />
  51902. var BABYLON;
  51903. (function (BABYLON) {
  51904. var Bone = (function (_super) {
  51905. __extends(Bone, _super);
  51906. function Bone(name, skeleton, parentBone, matrix, restPose) {
  51907. if (parentBone === void 0) { parentBone = null; }
  51908. var _this = _super.call(this, name, skeleton.getScene()) || this;
  51909. _this.name = name;
  51910. _this.children = new Array();
  51911. _this.animations = new Array();
  51912. _this._worldTransform = new BABYLON.Matrix();
  51913. _this._absoluteTransform = new BABYLON.Matrix();
  51914. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  51915. _this._scaleMatrix = BABYLON.Matrix.Identity();
  51916. _this._scaleVector = BABYLON.Vector3.One();
  51917. _this._negateScaleChildren = BABYLON.Vector3.One();
  51918. _this._scalingDeterminant = 1;
  51919. _this._skeleton = skeleton;
  51920. _this._localMatrix = matrix ? matrix : BABYLON.Matrix.Identity();
  51921. _this._baseMatrix = _this._localMatrix.clone();
  51922. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  51923. skeleton.bones.push(_this);
  51924. _this.setParent(parentBone, false);
  51925. _this._updateDifferenceMatrix();
  51926. return _this;
  51927. }
  51928. Object.defineProperty(Bone.prototype, "_matrix", {
  51929. get: function () {
  51930. return this._localMatrix;
  51931. },
  51932. set: function (val) {
  51933. if (this._localMatrix) {
  51934. this._localMatrix.copyFrom(val);
  51935. }
  51936. else {
  51937. this._localMatrix = val;
  51938. }
  51939. },
  51940. enumerable: true,
  51941. configurable: true
  51942. });
  51943. // Members
  51944. Bone.prototype.getSkeleton = function () {
  51945. return this._skeleton;
  51946. };
  51947. Bone.prototype.getParent = function () {
  51948. return this._parent;
  51949. };
  51950. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  51951. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  51952. if (this._parent === parent) {
  51953. return;
  51954. }
  51955. if (this._parent) {
  51956. var index = this._parent.children.indexOf(this);
  51957. if (index !== -1) {
  51958. this._parent.children.splice(index);
  51959. }
  51960. }
  51961. this._parent = parent;
  51962. if (this._parent) {
  51963. this._parent.children.push(this);
  51964. }
  51965. if (updateDifferenceMatrix) {
  51966. this._updateDifferenceMatrix();
  51967. }
  51968. };
  51969. Bone.prototype.getLocalMatrix = function () {
  51970. return this._localMatrix;
  51971. };
  51972. Bone.prototype.getBaseMatrix = function () {
  51973. return this._baseMatrix;
  51974. };
  51975. Bone.prototype.getRestPose = function () {
  51976. return this._restPose;
  51977. };
  51978. Bone.prototype.returnToRest = function () {
  51979. this.updateMatrix(this._restPose.clone());
  51980. };
  51981. Bone.prototype.getWorldMatrix = function () {
  51982. return this._worldTransform;
  51983. };
  51984. Bone.prototype.getInvertedAbsoluteTransform = function () {
  51985. return this._invertedAbsoluteTransform;
  51986. };
  51987. Bone.prototype.getAbsoluteTransform = function () {
  51988. return this._absoluteTransform;
  51989. };
  51990. Object.defineProperty(Bone.prototype, "position", {
  51991. // Properties (matches AbstractMesh properties)
  51992. get: function () {
  51993. return this.getPosition();
  51994. },
  51995. set: function (newPosition) {
  51996. this.setPosition(newPosition);
  51997. },
  51998. enumerable: true,
  51999. configurable: true
  52000. });
  52001. Object.defineProperty(Bone.prototype, "rotation", {
  52002. get: function () {
  52003. return this.getRotation();
  52004. },
  52005. set: function (newRotation) {
  52006. this.setRotation(newRotation);
  52007. },
  52008. enumerable: true,
  52009. configurable: true
  52010. });
  52011. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  52012. get: function () {
  52013. return this.getRotationQuaternion();
  52014. },
  52015. set: function (newRotation) {
  52016. this.setRotationQuaternion(newRotation);
  52017. },
  52018. enumerable: true,
  52019. configurable: true
  52020. });
  52021. Object.defineProperty(Bone.prototype, "scaling", {
  52022. get: function () {
  52023. return this.getScale();
  52024. },
  52025. set: function (newScaling) {
  52026. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  52027. },
  52028. enumerable: true,
  52029. configurable: true
  52030. });
  52031. // Methods
  52032. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  52033. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  52034. this._baseMatrix = matrix.clone();
  52035. this._localMatrix = matrix.clone();
  52036. this._skeleton._markAsDirty();
  52037. if (updateDifferenceMatrix) {
  52038. this._updateDifferenceMatrix();
  52039. }
  52040. };
  52041. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  52042. if (!rootMatrix) {
  52043. rootMatrix = this._baseMatrix;
  52044. }
  52045. if (this._parent) {
  52046. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  52047. }
  52048. else {
  52049. this._absoluteTransform.copyFrom(rootMatrix);
  52050. }
  52051. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  52052. for (var index = 0; index < this.children.length; index++) {
  52053. this.children[index]._updateDifferenceMatrix();
  52054. }
  52055. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  52056. };
  52057. Bone.prototype.markAsDirty = function () {
  52058. this._currentRenderId++;
  52059. this._skeleton._markAsDirty();
  52060. };
  52061. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  52062. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  52063. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  52064. // all animation may be coming from a library skeleton, so may need to create animation
  52065. if (this.animations.length === 0) {
  52066. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  52067. this.animations[0].setKeys([]);
  52068. }
  52069. // get animation info / verify there is such a range from the source bone
  52070. var sourceRange = source.animations[0].getRange(rangeName);
  52071. if (!sourceRange) {
  52072. return false;
  52073. }
  52074. var from = sourceRange.from;
  52075. var to = sourceRange.to;
  52076. var sourceKeys = source.animations[0].getKeys();
  52077. // rescaling prep
  52078. var sourceBoneLength = source.length;
  52079. var sourceParent = source.getParent();
  52080. var parent = this.getParent();
  52081. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  52082. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  52083. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  52084. var destKeys = this.animations[0].getKeys();
  52085. // loop vars declaration
  52086. var orig;
  52087. var origTranslation;
  52088. var mat;
  52089. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  52090. orig = sourceKeys[key];
  52091. if (orig.frame >= from && orig.frame <= to) {
  52092. if (rescaleAsRequired) {
  52093. mat = orig.value.clone();
  52094. // scale based on parent ratio, when bone has parent
  52095. if (parentScalingReqd) {
  52096. origTranslation = mat.getTranslation();
  52097. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  52098. // scale based on skeleton dimension ratio when root bone, and value is passed
  52099. }
  52100. else if (dimensionsScalingReqd) {
  52101. origTranslation = mat.getTranslation();
  52102. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  52103. // use original when root bone, and no data for skelDimensionsRatio
  52104. }
  52105. else {
  52106. mat = orig.value;
  52107. }
  52108. }
  52109. else {
  52110. mat = orig.value;
  52111. }
  52112. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  52113. }
  52114. }
  52115. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  52116. return true;
  52117. };
  52118. /**
  52119. * Translate the bone in local or world space.
  52120. * @param vec The amount to translate the bone.
  52121. * @param space The space that the translation is in.
  52122. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52123. */
  52124. Bone.prototype.translate = function (vec, space, mesh) {
  52125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52126. var lm = this.getLocalMatrix();
  52127. if (space == BABYLON.Space.LOCAL) {
  52128. lm.m[12] += vec.x;
  52129. lm.m[13] += vec.y;
  52130. lm.m[14] += vec.z;
  52131. }
  52132. else {
  52133. var wm;
  52134. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52135. if (mesh) {
  52136. wm = mesh.getWorldMatrix();
  52137. }
  52138. this._skeleton.computeAbsoluteTransforms();
  52139. var tmat = Bone._tmpMats[0];
  52140. var tvec = Bone._tmpVecs[0];
  52141. if (mesh) {
  52142. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52143. tmat.multiplyToRef(wm, tmat);
  52144. }
  52145. else {
  52146. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52147. }
  52148. tmat.m[12] = 0;
  52149. tmat.m[13] = 0;
  52150. tmat.m[14] = 0;
  52151. tmat.invert();
  52152. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  52153. lm.m[12] += tvec.x;
  52154. lm.m[13] += tvec.y;
  52155. lm.m[14] += tvec.z;
  52156. }
  52157. this.markAsDirty();
  52158. };
  52159. /**
  52160. * Set the postion of the bone in local or world space.
  52161. * @param position The position to set the bone.
  52162. * @param space The space that the position is in.
  52163. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52164. */
  52165. Bone.prototype.setPosition = function (position, space, mesh) {
  52166. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52167. var lm = this.getLocalMatrix();
  52168. if (space == BABYLON.Space.LOCAL) {
  52169. lm.m[12] = position.x;
  52170. lm.m[13] = position.y;
  52171. lm.m[14] = position.z;
  52172. }
  52173. else {
  52174. var wm;
  52175. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52176. if (mesh) {
  52177. wm = mesh.getWorldMatrix();
  52178. }
  52179. this._skeleton.computeAbsoluteTransforms();
  52180. var tmat = Bone._tmpMats[0];
  52181. var vec = Bone._tmpVecs[0];
  52182. if (mesh) {
  52183. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52184. tmat.multiplyToRef(wm, tmat);
  52185. }
  52186. else {
  52187. tmat.copyFrom(this._parent.getAbsoluteTransform());
  52188. }
  52189. tmat.invert();
  52190. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  52191. lm.m[12] = vec.x;
  52192. lm.m[13] = vec.y;
  52193. lm.m[14] = vec.z;
  52194. }
  52195. this.markAsDirty();
  52196. };
  52197. /**
  52198. * Set the absolute postion of the bone (world space).
  52199. * @param position The position to set the bone.
  52200. * @param mesh The mesh that this bone is attached to.
  52201. */
  52202. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  52203. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  52204. };
  52205. /**
  52206. * Set the scale of the bone on the x, y and z axes.
  52207. * @param x The scale of the bone on the x axis.
  52208. * @param x The scale of the bone on the y axis.
  52209. * @param z The scale of the bone on the z axis.
  52210. * @param scaleChildren Set this to true if children of the bone should be scaled.
  52211. */
  52212. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  52213. if (scaleChildren === void 0) { scaleChildren = false; }
  52214. if (this.animations[0] && !this.animations[0].isStopped()) {
  52215. if (!scaleChildren) {
  52216. this._negateScaleChildren.x = 1 / x;
  52217. this._negateScaleChildren.y = 1 / y;
  52218. this._negateScaleChildren.z = 1 / z;
  52219. }
  52220. this._syncScaleVector();
  52221. }
  52222. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  52223. };
  52224. /**
  52225. * Scale the bone on the x, y and z axes.
  52226. * @param x The amount to scale the bone on the x axis.
  52227. * @param x The amount to scale the bone on the y axis.
  52228. * @param z The amount to scale the bone on the z axis.
  52229. * @param scaleChildren Set this to true if children of the bone should be scaled.
  52230. */
  52231. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  52232. if (scaleChildren === void 0) { scaleChildren = false; }
  52233. var locMat = this.getLocalMatrix();
  52234. var origLocMat = Bone._tmpMats[0];
  52235. origLocMat.copyFrom(locMat);
  52236. var origLocMatInv = Bone._tmpMats[1];
  52237. origLocMatInv.copyFrom(origLocMat);
  52238. origLocMatInv.invert();
  52239. var scaleMat = Bone._tmpMats[2];
  52240. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  52241. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  52242. this._scaleVector.x *= x;
  52243. this._scaleVector.y *= y;
  52244. this._scaleVector.z *= z;
  52245. locMat.multiplyToRef(origLocMatInv, locMat);
  52246. locMat.multiplyToRef(scaleMat, locMat);
  52247. locMat.multiplyToRef(origLocMat, locMat);
  52248. var parent = this.getParent();
  52249. if (parent) {
  52250. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  52251. }
  52252. else {
  52253. this.getAbsoluteTransform().copyFrom(locMat);
  52254. }
  52255. var len = this.children.length;
  52256. scaleMat.invert();
  52257. for (var i = 0; i < len; i++) {
  52258. var child = this.children[i];
  52259. var cm = child.getLocalMatrix();
  52260. cm.multiplyToRef(scaleMat, cm);
  52261. var lm = child.getLocalMatrix();
  52262. lm.m[12] *= x;
  52263. lm.m[13] *= y;
  52264. lm.m[14] *= z;
  52265. }
  52266. this.computeAbsoluteTransforms();
  52267. if (scaleChildren) {
  52268. for (var i = 0; i < len; i++) {
  52269. this.children[i].scale(x, y, z, scaleChildren);
  52270. }
  52271. }
  52272. this.markAsDirty();
  52273. };
  52274. /**
  52275. * Set the yaw, pitch, and roll of the bone in local or world space.
  52276. * @param yaw The rotation of the bone on the y axis.
  52277. * @param pitch The rotation of the bone on the x axis.
  52278. * @param roll The rotation of the bone on the z axis.
  52279. * @param space The space that the axes of rotation are in.
  52280. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52281. */
  52282. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  52283. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52284. var rotMat = Bone._tmpMats[0];
  52285. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  52286. var rotMatInv = Bone._tmpMats[1];
  52287. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52288. rotMatInv.multiplyToRef(rotMat, rotMat);
  52289. this._rotateWithMatrix(rotMat, space, mesh);
  52290. };
  52291. /**
  52292. * Rotate the bone on an axis in local or world space.
  52293. * @param axis The axis to rotate the bone on.
  52294. * @param amount The amount to rotate the bone.
  52295. * @param space The space that the axis is in.
  52296. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52297. */
  52298. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  52299. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52300. var rmat = Bone._tmpMats[0];
  52301. rmat.m[12] = 0;
  52302. rmat.m[13] = 0;
  52303. rmat.m[14] = 0;
  52304. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  52305. this._rotateWithMatrix(rmat, space, mesh);
  52306. };
  52307. /**
  52308. * Set the rotation of the bone to a particular axis angle in local or world space.
  52309. * @param axis The axis to rotate the bone on.
  52310. * @param angle The angle that the bone should be rotated to.
  52311. * @param space The space that the axis is in.
  52312. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52313. */
  52314. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  52315. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52316. var rotMat = Bone._tmpMats[0];
  52317. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  52318. var rotMatInv = Bone._tmpMats[1];
  52319. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52320. rotMatInv.multiplyToRef(rotMat, rotMat);
  52321. this._rotateWithMatrix(rotMat, space, mesh);
  52322. };
  52323. /**
  52324. * Set the euler rotation of the bone in local of world space.
  52325. * @param rotation The euler rotation that the bone should be set to.
  52326. * @param space The space that the rotation is in.
  52327. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52328. */
  52329. Bone.prototype.setRotation = function (rotation, space, mesh) {
  52330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52331. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  52332. };
  52333. /**
  52334. * Set the quaternion rotation of the bone in local of world space.
  52335. * @param quat The quaternion rotation that the bone should be set to.
  52336. * @param space The space that the rotation is in.
  52337. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52338. */
  52339. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  52340. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52341. var rotMatInv = Bone._tmpMats[0];
  52342. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52343. var rotMat = Bone._tmpMats[1];
  52344. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  52345. rotMatInv.multiplyToRef(rotMat, rotMat);
  52346. this._rotateWithMatrix(rotMat, space, mesh);
  52347. };
  52348. /**
  52349. * Set the rotation matrix of the bone in local of world space.
  52350. * @param rotMat The rotation matrix that the bone should be set to.
  52351. * @param space The space that the rotation is in.
  52352. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52353. */
  52354. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  52355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52356. var rotMatInv = Bone._tmpMats[0];
  52357. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  52358. var rotMat2 = Bone._tmpMats[1];
  52359. rotMat2.copyFrom(rotMat);
  52360. rotMatInv.multiplyToRef(rotMat, rotMat2);
  52361. this._rotateWithMatrix(rotMat2, space, mesh);
  52362. };
  52363. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  52364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52365. var lmat = this.getLocalMatrix();
  52366. var lx = lmat.m[12];
  52367. var ly = lmat.m[13];
  52368. var lz = lmat.m[14];
  52369. var parent = this.getParent();
  52370. var parentScale = Bone._tmpMats[3];
  52371. var parentScaleInv = Bone._tmpMats[4];
  52372. if (parent) {
  52373. if (space == BABYLON.Space.WORLD) {
  52374. if (mesh) {
  52375. parentScale.copyFrom(mesh.getWorldMatrix());
  52376. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  52377. }
  52378. else {
  52379. parentScale.copyFrom(parent.getAbsoluteTransform());
  52380. }
  52381. }
  52382. else {
  52383. parentScale = parent._scaleMatrix;
  52384. }
  52385. parentScaleInv.copyFrom(parentScale);
  52386. parentScaleInv.invert();
  52387. lmat.multiplyToRef(parentScale, lmat);
  52388. lmat.multiplyToRef(rmat, lmat);
  52389. lmat.multiplyToRef(parentScaleInv, lmat);
  52390. }
  52391. else {
  52392. if (space == BABYLON.Space.WORLD && mesh) {
  52393. parentScale.copyFrom(mesh.getWorldMatrix());
  52394. parentScaleInv.copyFrom(parentScale);
  52395. parentScaleInv.invert();
  52396. lmat.multiplyToRef(parentScale, lmat);
  52397. lmat.multiplyToRef(rmat, lmat);
  52398. lmat.multiplyToRef(parentScaleInv, lmat);
  52399. }
  52400. else {
  52401. lmat.multiplyToRef(rmat, lmat);
  52402. }
  52403. }
  52404. lmat.m[12] = lx;
  52405. lmat.m[13] = ly;
  52406. lmat.m[14] = lz;
  52407. this.computeAbsoluteTransforms();
  52408. this.markAsDirty();
  52409. };
  52410. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  52411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52412. if (space == BABYLON.Space.WORLD) {
  52413. var scaleMatrix = Bone._tmpMats[2];
  52414. scaleMatrix.copyFrom(this._scaleMatrix);
  52415. rotMatInv.copyFrom(this.getAbsoluteTransform());
  52416. if (mesh) {
  52417. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  52418. var meshScale = Bone._tmpMats[3];
  52419. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  52420. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  52421. }
  52422. rotMatInv.invert();
  52423. scaleMatrix.m[0] *= this._scalingDeterminant;
  52424. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  52425. }
  52426. else {
  52427. rotMatInv.copyFrom(this.getLocalMatrix());
  52428. rotMatInv.invert();
  52429. var scaleMatrix = Bone._tmpMats[2];
  52430. scaleMatrix.copyFrom(this._scaleMatrix);
  52431. if (this._parent) {
  52432. var pscaleMatrix = Bone._tmpMats[3];
  52433. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  52434. pscaleMatrix.invert();
  52435. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  52436. }
  52437. else {
  52438. scaleMatrix.m[0] *= this._scalingDeterminant;
  52439. }
  52440. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  52441. }
  52442. };
  52443. /**
  52444. * Get the scale of the bone
  52445. * @returns the scale of the bone
  52446. */
  52447. Bone.prototype.getScale = function () {
  52448. return this._scaleVector.clone();
  52449. };
  52450. /**
  52451. * Copy the scale of the bone to a vector3.
  52452. * @param result The vector3 to copy the scale to
  52453. */
  52454. Bone.prototype.getScaleToRef = function (result) {
  52455. result.copyFrom(this._scaleVector);
  52456. };
  52457. /**
  52458. * Get the position of the bone in local or world space.
  52459. * @param space The space that the returned position is in.
  52460. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52461. * @returns The position of the bone
  52462. */
  52463. Bone.prototype.getPosition = function (space, mesh) {
  52464. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52465. var pos = BABYLON.Vector3.Zero();
  52466. this.getPositionToRef(space, mesh, pos);
  52467. return pos;
  52468. };
  52469. /**
  52470. * Copy the position of the bone to a vector3 in local or world space.
  52471. * @param space The space that the returned position is in.
  52472. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52473. * @param result The vector3 to copy the position to.
  52474. */
  52475. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  52476. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52477. if (space == BABYLON.Space.LOCAL) {
  52478. var lm = this.getLocalMatrix();
  52479. result.x = lm.m[12];
  52480. result.y = lm.m[13];
  52481. result.z = lm.m[14];
  52482. }
  52483. else {
  52484. var wm;
  52485. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52486. if (mesh) {
  52487. wm = mesh.getWorldMatrix();
  52488. }
  52489. this._skeleton.computeAbsoluteTransforms();
  52490. var tmat = Bone._tmpMats[0];
  52491. if (mesh) {
  52492. tmat.copyFrom(this.getAbsoluteTransform());
  52493. tmat.multiplyToRef(wm, tmat);
  52494. }
  52495. else {
  52496. tmat = this.getAbsoluteTransform();
  52497. }
  52498. result.x = tmat.m[12];
  52499. result.y = tmat.m[13];
  52500. result.z = tmat.m[14];
  52501. }
  52502. };
  52503. /**
  52504. * Get the absolute position of the bone (world space).
  52505. * @param mesh The mesh that this bone is attached to.
  52506. * @returns The absolute position of the bone
  52507. */
  52508. Bone.prototype.getAbsolutePosition = function (mesh) {
  52509. var pos = BABYLON.Vector3.Zero();
  52510. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  52511. return pos;
  52512. };
  52513. /**
  52514. * Copy the absolute position of the bone (world space) to the result param.
  52515. * @param mesh The mesh that this bone is attached to.
  52516. * @param result The vector3 to copy the absolute position to.
  52517. */
  52518. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  52519. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  52520. };
  52521. /**
  52522. * Compute the absolute transforms of this bone and its children.
  52523. */
  52524. Bone.prototype.computeAbsoluteTransforms = function () {
  52525. if (this._parent) {
  52526. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  52527. }
  52528. else {
  52529. this._absoluteTransform.copyFrom(this._localMatrix);
  52530. var poseMatrix = this._skeleton.getPoseMatrix();
  52531. if (poseMatrix) {
  52532. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  52533. }
  52534. }
  52535. var children = this.children;
  52536. var len = children.length;
  52537. for (var i = 0; i < len; i++) {
  52538. children[i].computeAbsoluteTransforms();
  52539. }
  52540. };
  52541. Bone.prototype._syncScaleVector = function () {
  52542. var lm = this.getLocalMatrix();
  52543. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  52544. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  52545. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  52546. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  52547. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  52548. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  52549. this._scaleVector.x = xs * Math.sqrt(xsq);
  52550. this._scaleVector.y = ys * Math.sqrt(ysq);
  52551. this._scaleVector.z = zs * Math.sqrt(zsq);
  52552. if (this._parent) {
  52553. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  52554. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  52555. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  52556. }
  52557. 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);
  52558. };
  52559. /**
  52560. * Get the world direction from an axis that is in the local space of the bone.
  52561. * @param localAxis The local direction that is used to compute the world direction.
  52562. * @param mesh The mesh that this bone is attached to.
  52563. * @returns The world direction
  52564. */
  52565. Bone.prototype.getDirection = function (localAxis, mesh) {
  52566. var result = BABYLON.Vector3.Zero();
  52567. this.getDirectionToRef(localAxis, mesh, result);
  52568. return result;
  52569. };
  52570. /**
  52571. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  52572. * @param localAxis The local direction that is used to compute the world direction.
  52573. * @param mesh The mesh that this bone is attached to.
  52574. * @param result The vector3 that the world direction will be copied to.
  52575. */
  52576. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  52577. var wm;
  52578. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52579. if (mesh) {
  52580. wm = mesh.getWorldMatrix();
  52581. }
  52582. this._skeleton.computeAbsoluteTransforms();
  52583. var mat = Bone._tmpMats[0];
  52584. mat.copyFrom(this.getAbsoluteTransform());
  52585. if (mesh) {
  52586. mat.multiplyToRef(wm, mat);
  52587. }
  52588. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  52589. result.normalize();
  52590. };
  52591. /**
  52592. * Get the euler rotation of the bone in local or world space.
  52593. * @param space The space that the rotation should be in.
  52594. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52595. * @returns The euler rotation
  52596. */
  52597. Bone.prototype.getRotation = function (space, mesh) {
  52598. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52599. var result = BABYLON.Vector3.Zero();
  52600. this.getRotationToRef(space, mesh, result);
  52601. return result;
  52602. };
  52603. /**
  52604. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  52605. * @param space The space that the rotation should be in.
  52606. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52607. * @param result The vector3 that the rotation should be copied to.
  52608. */
  52609. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  52610. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52611. var quat = Bone._tmpQuat;
  52612. this.getRotationQuaternionToRef(space, mesh, quat);
  52613. quat.toEulerAnglesToRef(result);
  52614. };
  52615. /**
  52616. * Get the quaternion rotation of the bone in either local or world space.
  52617. * @param space The space that the rotation should be in.
  52618. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52619. * @returns The quaternion rotation
  52620. */
  52621. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  52622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52623. var result = BABYLON.Quaternion.Identity();
  52624. this.getRotationQuaternionToRef(space, mesh, result);
  52625. return result;
  52626. };
  52627. /**
  52628. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  52629. * @param space The space that the rotation should be in.
  52630. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52631. * @param result The quaternion that the rotation should be copied to.
  52632. */
  52633. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  52634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52635. if (space == BABYLON.Space.LOCAL) {
  52636. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  52637. }
  52638. else {
  52639. var mat = Bone._tmpMats[0];
  52640. var amat = this.getAbsoluteTransform();
  52641. if (mesh) {
  52642. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  52643. }
  52644. else {
  52645. mat.copyFrom(amat);
  52646. }
  52647. mat.m[0] *= this._scalingDeterminant;
  52648. mat.m[1] *= this._scalingDeterminant;
  52649. mat.m[2] *= this._scalingDeterminant;
  52650. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  52651. }
  52652. };
  52653. /**
  52654. * Get the rotation matrix of the bone in local or world space.
  52655. * @param space The space that the rotation should be in.
  52656. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52657. * @returns The rotation matrix
  52658. */
  52659. Bone.prototype.getRotationMatrix = function (space, mesh) {
  52660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52661. var result = BABYLON.Matrix.Identity();
  52662. this.getRotationMatrixToRef(space, mesh, result);
  52663. return result;
  52664. };
  52665. /**
  52666. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  52667. * @param space The space that the rotation should be in.
  52668. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  52669. * @param result The quaternion that the rotation should be copied to.
  52670. */
  52671. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  52672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  52673. if (space == BABYLON.Space.LOCAL) {
  52674. this.getLocalMatrix().getRotationMatrixToRef(result);
  52675. }
  52676. else {
  52677. var mat = Bone._tmpMats[0];
  52678. var amat = this.getAbsoluteTransform();
  52679. if (mesh) {
  52680. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  52681. }
  52682. else {
  52683. mat.copyFrom(amat);
  52684. }
  52685. mat.m[0] *= this._scalingDeterminant;
  52686. mat.m[1] *= this._scalingDeterminant;
  52687. mat.m[2] *= this._scalingDeterminant;
  52688. mat.getRotationMatrixToRef(result);
  52689. }
  52690. };
  52691. /**
  52692. * Get the world position of a point that is in the local space of the bone.
  52693. * @param position The local position
  52694. * @param mesh The mesh that this bone is attached to.
  52695. * @returns The world position
  52696. */
  52697. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  52698. var result = BABYLON.Vector3.Zero();
  52699. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  52700. return result;
  52701. };
  52702. /**
  52703. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  52704. * @param position The local position
  52705. * @param mesh The mesh that this bone is attached to.
  52706. * @param result The vector3 that the world position should be copied to.
  52707. */
  52708. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  52709. var wm;
  52710. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52711. if (mesh) {
  52712. wm = mesh.getWorldMatrix();
  52713. }
  52714. this._skeleton.computeAbsoluteTransforms();
  52715. var tmat = Bone._tmpMats[0];
  52716. if (mesh) {
  52717. tmat.copyFrom(this.getAbsoluteTransform());
  52718. tmat.multiplyToRef(wm, tmat);
  52719. }
  52720. else {
  52721. tmat = this.getAbsoluteTransform();
  52722. }
  52723. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  52724. };
  52725. /**
  52726. * Get the local position of a point that is in world space.
  52727. * @param position The world position
  52728. * @param mesh The mesh that this bone is attached to.
  52729. * @returns The local position
  52730. */
  52731. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  52732. var result = BABYLON.Vector3.Zero();
  52733. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  52734. return result;
  52735. };
  52736. /**
  52737. * Get the local position of a point that is in world space and copy it to the result param.
  52738. * @param position The world position
  52739. * @param mesh The mesh that this bone is attached to.
  52740. * @param result The vector3 that the local position should be copied to.
  52741. */
  52742. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  52743. var wm;
  52744. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  52745. if (mesh) {
  52746. wm = mesh.getWorldMatrix();
  52747. }
  52748. this._skeleton.computeAbsoluteTransforms();
  52749. var tmat = Bone._tmpMats[0];
  52750. tmat.copyFrom(this.getAbsoluteTransform());
  52751. if (mesh) {
  52752. tmat.multiplyToRef(wm, tmat);
  52753. }
  52754. tmat.invert();
  52755. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  52756. };
  52757. return Bone;
  52758. }(BABYLON.Node));
  52759. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52760. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  52761. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52762. BABYLON.Bone = Bone;
  52763. })(BABYLON || (BABYLON = {}));
  52764. //# sourceMappingURL=babylon.bone.js.map
  52765. var BABYLON;
  52766. (function (BABYLON) {
  52767. var BoneIKController = (function () {
  52768. function BoneIKController(mesh, bone, options) {
  52769. this.targetPosition = BABYLON.Vector3.Zero();
  52770. this.poleTargetPosition = BABYLON.Vector3.Zero();
  52771. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  52772. this.poleAngle = 0;
  52773. this.slerpAmount = 1;
  52774. this._bone1Quat = BABYLON.Quaternion.Identity();
  52775. this._bone1Mat = BABYLON.Matrix.Identity();
  52776. this._bone2Ang = Math.PI;
  52777. this._maxAngle = Math.PI;
  52778. this._rightHandedSystem = false;
  52779. this._bendAxis = BABYLON.Vector3.Right();
  52780. this._slerping = false;
  52781. this._adjustRoll = 0;
  52782. this._bone2 = bone;
  52783. this._bone1 = bone.getParent();
  52784. this.mesh = mesh;
  52785. var bonePos = bone.getPosition();
  52786. if (bone.getAbsoluteTransform().determinant() > 0) {
  52787. this._rightHandedSystem = true;
  52788. this._bendAxis.x = 0;
  52789. this._bendAxis.y = 0;
  52790. this._bendAxis.z = -1;
  52791. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  52792. this._adjustRoll = Math.PI * .5;
  52793. this._bendAxis.z = 1;
  52794. }
  52795. }
  52796. if (this._bone1.length) {
  52797. var boneScale1 = this._bone1.getScale();
  52798. var boneScale2 = this._bone2.getScale();
  52799. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  52800. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  52801. }
  52802. else if (this._bone1.children[0]) {
  52803. mesh.computeWorldMatrix(true);
  52804. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  52805. var pos2 = this._bone2.getAbsolutePosition(mesh);
  52806. var pos3 = this._bone1.getAbsolutePosition(mesh);
  52807. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  52808. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  52809. }
  52810. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  52811. this.maxAngle = Math.PI;
  52812. if (options) {
  52813. if (options.targetMesh) {
  52814. this.targetMesh = options.targetMesh;
  52815. this.targetMesh.computeWorldMatrix(true);
  52816. }
  52817. if (options.poleTargetMesh) {
  52818. this.poleTargetMesh = options.poleTargetMesh;
  52819. this.poleTargetMesh.computeWorldMatrix(true);
  52820. }
  52821. else if (options.poleTargetBone) {
  52822. this.poleTargetBone = options.poleTargetBone;
  52823. }
  52824. else if (this._bone1.getParent()) {
  52825. this.poleTargetBone = this._bone1.getParent();
  52826. }
  52827. if (options.poleTargetLocalOffset) {
  52828. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  52829. }
  52830. if (options.poleAngle) {
  52831. this.poleAngle = options.poleAngle;
  52832. }
  52833. if (options.bendAxis) {
  52834. this._bendAxis.copyFrom(options.bendAxis);
  52835. }
  52836. if (options.maxAngle) {
  52837. this.maxAngle = options.maxAngle;
  52838. }
  52839. if (options.slerpAmount) {
  52840. this.slerpAmount = options.slerpAmount;
  52841. }
  52842. }
  52843. }
  52844. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  52845. get: function () {
  52846. return this._maxAngle;
  52847. },
  52848. set: function (value) {
  52849. this._setMaxAngle(value);
  52850. },
  52851. enumerable: true,
  52852. configurable: true
  52853. });
  52854. BoneIKController.prototype._setMaxAngle = function (ang) {
  52855. if (ang < 0) {
  52856. ang = 0;
  52857. }
  52858. if (ang > Math.PI || ang == undefined) {
  52859. ang = Math.PI;
  52860. }
  52861. this._maxAngle = ang;
  52862. var a = this._bone1Length;
  52863. var b = this._bone2Length;
  52864. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  52865. };
  52866. BoneIKController.prototype.update = function () {
  52867. var bone1 = this._bone1;
  52868. var target = this.targetPosition;
  52869. var poleTarget = this.poleTargetPosition;
  52870. var mat1 = BoneIKController._tmpMats[0];
  52871. var mat2 = BoneIKController._tmpMats[1];
  52872. if (this.targetMesh) {
  52873. target.copyFrom(this.targetMesh.getAbsolutePosition());
  52874. }
  52875. if (this.poleTargetBone) {
  52876. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  52877. }
  52878. else if (this.poleTargetMesh) {
  52879. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  52880. }
  52881. var bonePos = BoneIKController._tmpVecs[0];
  52882. var zaxis = BoneIKController._tmpVecs[1];
  52883. var xaxis = BoneIKController._tmpVecs[2];
  52884. var yaxis = BoneIKController._tmpVecs[3];
  52885. var upAxis = BoneIKController._tmpVecs[4];
  52886. var _tmpQuat = BoneIKController._tmpQuat;
  52887. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  52888. poleTarget.subtractToRef(bonePos, upAxis);
  52889. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  52890. upAxis.y = 1;
  52891. }
  52892. else {
  52893. upAxis.normalize();
  52894. }
  52895. target.subtractToRef(bonePos, yaxis);
  52896. yaxis.normalize();
  52897. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  52898. zaxis.normalize();
  52899. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  52900. xaxis.normalize();
  52901. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  52902. var a = this._bone1Length;
  52903. var b = this._bone2Length;
  52904. var c = BABYLON.Vector3.Distance(bonePos, target);
  52905. if (this._maxReach > 0) {
  52906. c = Math.min(this._maxReach, c);
  52907. }
  52908. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  52909. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  52910. if (acosa > 1) {
  52911. acosa = 1;
  52912. }
  52913. if (acosb > 1) {
  52914. acosb = 1;
  52915. }
  52916. if (acosa < -1) {
  52917. acosa = -1;
  52918. }
  52919. if (acosb < -1) {
  52920. acosb = -1;
  52921. }
  52922. var angA = Math.acos(acosa);
  52923. var angB = Math.acos(acosb);
  52924. var angC = -angA - angB;
  52925. if (this._rightHandedSystem) {
  52926. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  52927. mat2.multiplyToRef(mat1, mat1);
  52928. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  52929. mat2.multiplyToRef(mat1, mat1);
  52930. }
  52931. else {
  52932. var _tmpVec = BoneIKController._tmpVecs[5];
  52933. _tmpVec.copyFrom(this._bendAxis);
  52934. _tmpVec.x *= -1;
  52935. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  52936. mat2.multiplyToRef(mat1, mat1);
  52937. }
  52938. if (this.poleAngle) {
  52939. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  52940. mat1.multiplyToRef(mat2, mat1);
  52941. }
  52942. if (this.slerpAmount < 1) {
  52943. if (!this._slerping) {
  52944. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  52945. }
  52946. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  52947. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  52948. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  52949. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  52950. this._slerping = true;
  52951. }
  52952. else {
  52953. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  52954. this._bone1Mat.copyFrom(mat1);
  52955. this._slerping = false;
  52956. }
  52957. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  52958. this._bone2Ang = angC;
  52959. };
  52960. return BoneIKController;
  52961. }());
  52962. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52963. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  52964. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  52965. BABYLON.BoneIKController = BoneIKController;
  52966. })(BABYLON || (BABYLON = {}));
  52967. //# sourceMappingURL=babylon.boneIKController.js.map
  52968. var BABYLON;
  52969. (function (BABYLON) {
  52970. var BoneLookController = (function () {
  52971. /**
  52972. * Create a BoneLookController
  52973. * @param mesh the mesh that the bone belongs to
  52974. * @param bone the bone that will be looking to the target
  52975. * @param target the target Vector3 to look at
  52976. * @param settings optional settings:
  52977. * - maxYaw: the maximum angle the bone will yaw to
  52978. * - minYaw: the minimum angle the bone will yaw to
  52979. * - maxPitch: the maximum angle the bone will pitch to
  52980. * - minPitch: the minimum angle the bone will yaw to
  52981. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  52982. * - upAxis: the up axis of the coordinate system
  52983. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52984. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  52985. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  52986. * - adjustYaw: used to make an adjustment to the yaw of the bone
  52987. * - adjustPitch: used to make an adjustment to the pitch of the bone
  52988. * - adjustRoll: used to make an adjustment to the roll of the bone
  52989. **/
  52990. function BoneLookController(mesh, bone, target, options) {
  52991. /**
  52992. * The up axis of the coordinate system that is used when the bone is rotated.
  52993. */
  52994. this.upAxis = BABYLON.Vector3.Up();
  52995. /**
  52996. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  52997. */
  52998. this.upAxisSpace = BABYLON.Space.LOCAL;
  52999. /**
  53000. * Used to make an adjustment to the yaw of the bone.
  53001. */
  53002. this.adjustYaw = 0;
  53003. /**
  53004. * Used to make an adjustment to the pitch of the bone.
  53005. */
  53006. this.adjustPitch = 0;
  53007. /**
  53008. * Used to make an adjustment to the roll of the bone.
  53009. */
  53010. this.adjustRoll = 0;
  53011. /**
  53012. * 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).
  53013. */
  53014. this.slerpAmount = 1;
  53015. this._boneQuat = BABYLON.Quaternion.Identity();
  53016. this._slerping = false;
  53017. this._firstFrameSkipped = false;
  53018. this._fowardAxis = BABYLON.Vector3.Forward();
  53019. this.mesh = mesh;
  53020. this.bone = bone;
  53021. this.target = target;
  53022. if (options) {
  53023. if (options.adjustYaw) {
  53024. this.adjustYaw = options.adjustYaw;
  53025. }
  53026. if (options.adjustPitch) {
  53027. this.adjustPitch = options.adjustPitch;
  53028. }
  53029. if (options.adjustRoll) {
  53030. this.adjustRoll = options.adjustRoll;
  53031. }
  53032. if (options.maxYaw != null) {
  53033. this.maxYaw = options.maxYaw;
  53034. }
  53035. else {
  53036. this.maxYaw = Math.PI;
  53037. }
  53038. if (options.minYaw != null) {
  53039. this.minYaw = options.minYaw;
  53040. }
  53041. else {
  53042. this.minYaw = -Math.PI;
  53043. }
  53044. if (options.maxPitch != null) {
  53045. this.maxPitch = options.maxPitch;
  53046. }
  53047. else {
  53048. this.maxPitch = Math.PI;
  53049. }
  53050. if (options.minPitch != null) {
  53051. this.minPitch = options.minPitch;
  53052. }
  53053. else {
  53054. this.minPitch = -Math.PI;
  53055. }
  53056. if (options.slerpAmount != null) {
  53057. this.slerpAmount = options.slerpAmount;
  53058. }
  53059. if (options.upAxis != null) {
  53060. this.upAxis = options.upAxis;
  53061. }
  53062. if (options.upAxisSpace != null) {
  53063. this.upAxisSpace = options.upAxisSpace;
  53064. }
  53065. if (options.yawAxis != null || options.pitchAxis != null) {
  53066. var newYawAxis = BABYLON.Axis.Y;
  53067. var newPitchAxis = BABYLON.Axis.X;
  53068. if (options.yawAxis != null) {
  53069. newYawAxis = options.yawAxis.clone();
  53070. newYawAxis.normalize();
  53071. }
  53072. if (options.pitchAxis != null) {
  53073. newPitchAxis = options.pitchAxis.clone();
  53074. newPitchAxis.normalize();
  53075. }
  53076. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  53077. this._transformYawPitch = BABYLON.Matrix.Identity();
  53078. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  53079. this._transformYawPitchInv = this._transformYawPitch.clone();
  53080. this._transformYawPitch.invert();
  53081. }
  53082. }
  53083. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  53084. this.upAxisSpace = BABYLON.Space.LOCAL;
  53085. }
  53086. }
  53087. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  53088. /**
  53089. * Get/set the minimum yaw angle that the bone can look to.
  53090. */
  53091. get: function () {
  53092. return this._minYaw;
  53093. },
  53094. set: function (value) {
  53095. this._minYaw = value;
  53096. this._minYawSin = Math.sin(value);
  53097. this._minYawCos = Math.cos(value);
  53098. if (this._maxYaw != null) {
  53099. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  53100. this._yawRange = this._maxYaw - this._minYaw;
  53101. }
  53102. },
  53103. enumerable: true,
  53104. configurable: true
  53105. });
  53106. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  53107. /**
  53108. * Get/set the maximum yaw angle that the bone can look to.
  53109. */
  53110. get: function () {
  53111. return this._maxYaw;
  53112. },
  53113. set: function (value) {
  53114. this._maxYaw = value;
  53115. this._maxYawSin = Math.sin(value);
  53116. this._maxYawCos = Math.cos(value);
  53117. if (this._minYaw != null) {
  53118. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  53119. this._yawRange = this._maxYaw - this._minYaw;
  53120. }
  53121. },
  53122. enumerable: true,
  53123. configurable: true
  53124. });
  53125. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  53126. /**
  53127. * Get/set the minimum pitch angle that the bone can look to.
  53128. */
  53129. get: function () {
  53130. return this._minPitch;
  53131. },
  53132. set: function (value) {
  53133. this._minPitch = value;
  53134. this._minPitchTan = Math.tan(value);
  53135. },
  53136. enumerable: true,
  53137. configurable: true
  53138. });
  53139. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  53140. /**
  53141. * Get/set the maximum pitch angle that the bone can look to.
  53142. */
  53143. get: function () {
  53144. return this._maxPitch;
  53145. },
  53146. set: function (value) {
  53147. this._maxPitch = value;
  53148. this._maxPitchTan = Math.tan(value);
  53149. },
  53150. enumerable: true,
  53151. configurable: true
  53152. });
  53153. /**
  53154. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  53155. */
  53156. BoneLookController.prototype.update = function () {
  53157. //skip the first frame when slerping so that the mesh rotation is correct
  53158. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  53159. this._firstFrameSkipped = true;
  53160. return;
  53161. }
  53162. var bone = this.bone;
  53163. var bonePos = BoneLookController._tmpVecs[0];
  53164. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  53165. var target = this.target;
  53166. var _tmpMat1 = BoneLookController._tmpMats[0];
  53167. var _tmpMat2 = BoneLookController._tmpMats[1];
  53168. var mesh = this.mesh;
  53169. var parentBone = bone.getParent();
  53170. var upAxis = BoneLookController._tmpVecs[1];
  53171. upAxis.copyFrom(this.upAxis);
  53172. if (this.upAxisSpace == BABYLON.Space.BONE) {
  53173. if (this._transformYawPitch) {
  53174. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  53175. }
  53176. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  53177. }
  53178. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  53179. mesh.getDirectionToRef(upAxis, upAxis);
  53180. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  53181. upAxis.normalize();
  53182. }
  53183. }
  53184. var checkYaw = false;
  53185. var checkPitch = false;
  53186. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  53187. checkYaw = true;
  53188. }
  53189. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  53190. checkPitch = true;
  53191. }
  53192. if (checkYaw || checkPitch) {
  53193. var spaceMat = BoneLookController._tmpMats[2];
  53194. var spaceMatInv = BoneLookController._tmpMats[3];
  53195. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  53196. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  53197. }
  53198. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  53199. spaceMat.copyFrom(mesh.getWorldMatrix());
  53200. }
  53201. else {
  53202. var forwardAxis = BoneLookController._tmpVecs[2];
  53203. forwardAxis.copyFrom(this._fowardAxis);
  53204. if (this._transformYawPitch) {
  53205. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  53206. }
  53207. if (parentBone) {
  53208. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  53209. }
  53210. else {
  53211. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  53212. }
  53213. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  53214. rightAxis.normalize();
  53215. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  53216. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  53217. }
  53218. spaceMat.invertToRef(spaceMatInv);
  53219. var xzlen;
  53220. if (checkPitch) {
  53221. var localTarget = BoneLookController._tmpVecs[3];
  53222. target.subtractToRef(bonePos, localTarget);
  53223. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  53224. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  53225. var pitch = Math.atan2(localTarget.y, xzlen);
  53226. var newPitch = pitch;
  53227. if (pitch > this._maxPitch) {
  53228. localTarget.y = this._maxPitchTan * xzlen;
  53229. newPitch = this._maxPitch;
  53230. }
  53231. else if (pitch < this._minPitch) {
  53232. localTarget.y = this._minPitchTan * xzlen;
  53233. newPitch = this._minPitch;
  53234. }
  53235. if (pitch != newPitch) {
  53236. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  53237. localTarget.addInPlace(bonePos);
  53238. target = localTarget;
  53239. }
  53240. }
  53241. if (checkYaw) {
  53242. var localTarget = BoneLookController._tmpVecs[4];
  53243. target.subtractToRef(bonePos, localTarget);
  53244. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  53245. var yaw = Math.atan2(localTarget.x, localTarget.z);
  53246. var newYaw = yaw;
  53247. if (yaw > this._maxYaw || yaw < this._minYaw) {
  53248. if (xzlen == null) {
  53249. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  53250. }
  53251. if (this._yawRange > Math.PI) {
  53252. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  53253. localTarget.z = this._maxYawCos * xzlen;
  53254. localTarget.x = this._maxYawSin * xzlen;
  53255. newYaw = this._maxYaw;
  53256. }
  53257. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  53258. localTarget.z = this._minYawCos * xzlen;
  53259. localTarget.x = this._minYawSin * xzlen;
  53260. newYaw = this._minYaw;
  53261. }
  53262. }
  53263. else {
  53264. if (yaw > this._maxYaw) {
  53265. localTarget.z = this._maxYawCos * xzlen;
  53266. localTarget.x = this._maxYawSin * xzlen;
  53267. newYaw = this._maxYaw;
  53268. }
  53269. else if (yaw < this._minYaw) {
  53270. localTarget.z = this._minYawCos * xzlen;
  53271. localTarget.x = this._minYawSin * xzlen;
  53272. newYaw = this._minYaw;
  53273. }
  53274. }
  53275. }
  53276. if (this._slerping && this._yawRange > Math.PI) {
  53277. //are we going to be crossing into the min/max region?
  53278. var boneFwd = BoneLookController._tmpVecs[8];
  53279. boneFwd.copyFrom(BABYLON.Axis.Z);
  53280. if (this._transformYawPitch) {
  53281. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  53282. }
  53283. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  53284. this._boneQuat.toRotationMatrix(boneRotMat);
  53285. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  53286. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  53287. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  53288. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  53289. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  53290. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  53291. if (angBtwTar > angBtwMidYaw) {
  53292. if (xzlen == null) {
  53293. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  53294. }
  53295. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  53296. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  53297. if (angBtwMin < angBtwMax) {
  53298. newYaw = boneYaw + Math.PI * .75;
  53299. localTarget.z = Math.cos(newYaw) * xzlen;
  53300. localTarget.x = Math.sin(newYaw) * xzlen;
  53301. }
  53302. else {
  53303. newYaw = boneYaw - Math.PI * .75;
  53304. localTarget.z = Math.cos(newYaw) * xzlen;
  53305. localTarget.x = Math.sin(newYaw) * xzlen;
  53306. }
  53307. }
  53308. }
  53309. if (yaw != newYaw) {
  53310. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  53311. localTarget.addInPlace(bonePos);
  53312. target = localTarget;
  53313. }
  53314. }
  53315. }
  53316. var zaxis = BoneLookController._tmpVecs[5];
  53317. var xaxis = BoneLookController._tmpVecs[6];
  53318. var yaxis = BoneLookController._tmpVecs[7];
  53319. var _tmpQuat = BoneLookController._tmpQuat;
  53320. target.subtractToRef(bonePos, zaxis);
  53321. zaxis.normalize();
  53322. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  53323. xaxis.normalize();
  53324. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  53325. yaxis.normalize();
  53326. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  53327. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  53328. return;
  53329. }
  53330. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  53331. return;
  53332. }
  53333. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  53334. return;
  53335. }
  53336. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  53337. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  53338. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  53339. }
  53340. if (this.slerpAmount < 1) {
  53341. if (!this._slerping) {
  53342. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  53343. }
  53344. if (this._transformYawPitch) {
  53345. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  53346. }
  53347. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  53348. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  53349. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  53350. this._slerping = true;
  53351. }
  53352. else {
  53353. if (this._transformYawPitch) {
  53354. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  53355. }
  53356. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  53357. this._slerping = false;
  53358. }
  53359. };
  53360. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  53361. var angDiff = ang2 - ang1;
  53362. angDiff %= Math.PI * 2;
  53363. if (angDiff > Math.PI) {
  53364. angDiff -= Math.PI * 2;
  53365. }
  53366. else if (angDiff < -Math.PI) {
  53367. angDiff += Math.PI * 2;
  53368. }
  53369. return angDiff;
  53370. };
  53371. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  53372. ang1 %= (2 * Math.PI);
  53373. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  53374. ang2 %= (2 * Math.PI);
  53375. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  53376. var ab = 0;
  53377. if (ang1 < ang2) {
  53378. ab = ang2 - ang1;
  53379. }
  53380. else {
  53381. ab = ang1 - ang2;
  53382. }
  53383. if (ab > Math.PI) {
  53384. ab = Math.PI * 2 - ab;
  53385. }
  53386. return ab;
  53387. };
  53388. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  53389. ang %= (2 * Math.PI);
  53390. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  53391. ang1 %= (2 * Math.PI);
  53392. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  53393. ang2 %= (2 * Math.PI);
  53394. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  53395. if (ang1 < ang2) {
  53396. if (ang > ang1 && ang < ang2) {
  53397. return true;
  53398. }
  53399. }
  53400. else {
  53401. if (ang > ang2 && ang < ang1) {
  53402. return true;
  53403. }
  53404. }
  53405. return false;
  53406. };
  53407. return BoneLookController;
  53408. }());
  53409. 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()];
  53410. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  53411. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  53412. BABYLON.BoneLookController = BoneLookController;
  53413. })(BABYLON || (BABYLON = {}));
  53414. //# sourceMappingURL=babylon.boneLookController.js.map
  53415. var BABYLON;
  53416. (function (BABYLON) {
  53417. var Skeleton = (function () {
  53418. function Skeleton(name, id, scene) {
  53419. this.name = name;
  53420. this.id = id;
  53421. this.bones = new Array();
  53422. this.needInitialSkinMatrix = false;
  53423. this._isDirty = true;
  53424. this._meshesWithPoseMatrix = new Array();
  53425. this._identity = BABYLON.Matrix.Identity();
  53426. this._ranges = {};
  53427. this._lastAbsoluteTransformsUpdateId = -1;
  53428. // Events
  53429. /**
  53430. * An event triggered before computing the skeleton's matrices
  53431. * @type {BABYLON.Observable}
  53432. */
  53433. this.onBeforeComputeObservable = new BABYLON.Observable();
  53434. this.bones = [];
  53435. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53436. scene.skeletons.push(this);
  53437. //make sure it will recalculate the matrix next time prepare is called.
  53438. this._isDirty = true;
  53439. }
  53440. // Members
  53441. Skeleton.prototype.getTransformMatrices = function (mesh) {
  53442. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  53443. return mesh._bonesTransformMatrices;
  53444. }
  53445. if (!this._transformMatrices) {
  53446. this.prepare();
  53447. }
  53448. return this._transformMatrices;
  53449. };
  53450. Skeleton.prototype.getScene = function () {
  53451. return this._scene;
  53452. };
  53453. // Methods
  53454. /**
  53455. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  53456. */
  53457. Skeleton.prototype.toString = function (fullDetails) {
  53458. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  53459. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  53460. if (fullDetails) {
  53461. ret += ", Ranges: {";
  53462. var first = true;
  53463. for (var name_1 in this._ranges) {
  53464. if (first) {
  53465. ret += ", ";
  53466. first = false;
  53467. }
  53468. ret += name_1;
  53469. }
  53470. ret += "}";
  53471. }
  53472. return ret;
  53473. };
  53474. /**
  53475. * Get bone's index searching by name
  53476. * @param {string} name is bone's name to search for
  53477. * @return {number} Indice of the bone. Returns -1 if not found
  53478. */
  53479. Skeleton.prototype.getBoneIndexByName = function (name) {
  53480. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  53481. if (this.bones[boneIndex].name === name) {
  53482. return boneIndex;
  53483. }
  53484. }
  53485. return -1;
  53486. };
  53487. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  53488. // check name not already in use
  53489. if (!this._ranges[name]) {
  53490. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  53491. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  53492. if (this.bones[i].animations[0]) {
  53493. this.bones[i].animations[0].createRange(name, from, to);
  53494. }
  53495. }
  53496. }
  53497. };
  53498. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  53499. if (deleteFrames === void 0) { deleteFrames = true; }
  53500. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  53501. if (this.bones[i].animations[0]) {
  53502. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  53503. }
  53504. }
  53505. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  53506. };
  53507. Skeleton.prototype.getAnimationRange = function (name) {
  53508. return this._ranges[name];
  53509. };
  53510. /**
  53511. * Returns as an Array, all AnimationRanges defined on this skeleton
  53512. */
  53513. Skeleton.prototype.getAnimationRanges = function () {
  53514. var animationRanges = [];
  53515. var name;
  53516. var i = 0;
  53517. for (name in this._ranges) {
  53518. animationRanges[i] = this._ranges[name];
  53519. i++;
  53520. }
  53521. return animationRanges;
  53522. };
  53523. /**
  53524. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  53525. */
  53526. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  53527. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  53528. if (this._ranges[name] || !source.getAnimationRange(name)) {
  53529. return false;
  53530. }
  53531. var ret = true;
  53532. var frameOffset = this._getHighestAnimationFrame() + 1;
  53533. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  53534. var boneDict = {};
  53535. var sourceBones = source.bones;
  53536. var nBones;
  53537. var i;
  53538. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  53539. boneDict[sourceBones[i].name] = sourceBones[i];
  53540. }
  53541. if (this.bones.length !== sourceBones.length) {
  53542. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  53543. ret = false;
  53544. }
  53545. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  53546. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  53547. var boneName = this.bones[i].name;
  53548. var sourceBone = boneDict[boneName];
  53549. if (sourceBone) {
  53550. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  53551. }
  53552. else {
  53553. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  53554. ret = false;
  53555. }
  53556. }
  53557. // do not call createAnimationRange(), since it also is done to bones, which was already done
  53558. var range = source.getAnimationRange(name);
  53559. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  53560. return ret;
  53561. };
  53562. Skeleton.prototype.returnToRest = function () {
  53563. for (var index = 0; index < this.bones.length; index++) {
  53564. this.bones[index].returnToRest();
  53565. }
  53566. };
  53567. Skeleton.prototype._getHighestAnimationFrame = function () {
  53568. var ret = 0;
  53569. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  53570. if (this.bones[i].animations[0]) {
  53571. var highest = this.bones[i].animations[0].getHighestFrame();
  53572. if (ret < highest) {
  53573. ret = highest;
  53574. }
  53575. }
  53576. }
  53577. return ret;
  53578. };
  53579. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  53580. var range = this.getAnimationRange(name);
  53581. if (!range) {
  53582. return null;
  53583. }
  53584. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  53585. };
  53586. Skeleton.prototype._markAsDirty = function () {
  53587. this._isDirty = true;
  53588. };
  53589. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  53590. this._meshesWithPoseMatrix.push(mesh);
  53591. };
  53592. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  53593. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  53594. if (index > -1) {
  53595. this._meshesWithPoseMatrix.splice(index, 1);
  53596. }
  53597. };
  53598. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  53599. this.onBeforeComputeObservable.notifyObservers(this);
  53600. for (var index = 0; index < this.bones.length; index++) {
  53601. var bone = this.bones[index];
  53602. var parentBone = bone.getParent();
  53603. if (parentBone) {
  53604. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  53605. }
  53606. else {
  53607. if (initialSkinMatrix) {
  53608. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  53609. }
  53610. else {
  53611. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  53612. }
  53613. }
  53614. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  53615. }
  53616. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  53617. };
  53618. Skeleton.prototype.prepare = function () {
  53619. if (!this._isDirty) {
  53620. return;
  53621. }
  53622. if (this.needInitialSkinMatrix) {
  53623. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  53624. var mesh = this._meshesWithPoseMatrix[index];
  53625. var poseMatrix = mesh.getPoseMatrix();
  53626. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  53627. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  53628. }
  53629. if (this._synchronizedWithMesh !== mesh) {
  53630. this._synchronizedWithMesh = mesh;
  53631. // Prepare bones
  53632. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  53633. var bone = this.bones[boneIndex];
  53634. if (!bone.getParent()) {
  53635. var matrix = bone.getBaseMatrix();
  53636. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  53637. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  53638. }
  53639. }
  53640. }
  53641. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  53642. }
  53643. }
  53644. else {
  53645. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  53646. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  53647. }
  53648. this._computeTransformMatrices(this._transformMatrices, null);
  53649. }
  53650. this._isDirty = false;
  53651. this._scene._activeBones.addCount(this.bones.length, false);
  53652. };
  53653. Skeleton.prototype.getAnimatables = function () {
  53654. if (!this._animatables || this._animatables.length !== this.bones.length) {
  53655. this._animatables = [];
  53656. for (var index = 0; index < this.bones.length; index++) {
  53657. this._animatables.push(this.bones[index]);
  53658. }
  53659. }
  53660. return this._animatables;
  53661. };
  53662. Skeleton.prototype.clone = function (name, id) {
  53663. var result = new Skeleton(name, id || name, this._scene);
  53664. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  53665. for (var index = 0; index < this.bones.length; index++) {
  53666. var source = this.bones[index];
  53667. var parentBone = null;
  53668. if (source.getParent()) {
  53669. var parentIndex = this.bones.indexOf(source.getParent());
  53670. parentBone = result.bones[parentIndex];
  53671. }
  53672. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  53673. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  53674. }
  53675. if (this._ranges) {
  53676. result._ranges = {};
  53677. for (var rangeName in this._ranges) {
  53678. result._ranges[rangeName] = this._ranges[rangeName].clone();
  53679. }
  53680. }
  53681. this._isDirty = true;
  53682. return result;
  53683. };
  53684. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  53685. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  53686. this.bones.forEach(function (bone) {
  53687. bone.animations.forEach(function (animation) {
  53688. animation.enableBlending = true;
  53689. animation.blendingSpeed = blendingSpeed;
  53690. });
  53691. });
  53692. };
  53693. Skeleton.prototype.dispose = function () {
  53694. this._meshesWithPoseMatrix = [];
  53695. // Animations
  53696. this.getScene().stopAnimation(this);
  53697. // Remove from scene
  53698. this.getScene().removeSkeleton(this);
  53699. };
  53700. Skeleton.prototype.serialize = function () {
  53701. var serializationObject = {};
  53702. serializationObject.name = this.name;
  53703. serializationObject.id = this.id;
  53704. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  53705. serializationObject.bones = [];
  53706. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  53707. for (var index = 0; index < this.bones.length; index++) {
  53708. var bone = this.bones[index];
  53709. var serializedBone = {
  53710. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  53711. name: bone.name,
  53712. matrix: bone.getBaseMatrix().toArray(),
  53713. rest: bone.getRestPose().toArray()
  53714. };
  53715. serializationObject.bones.push(serializedBone);
  53716. if (bone.length) {
  53717. serializedBone.length = bone.length;
  53718. }
  53719. if (bone.animations && bone.animations.length > 0) {
  53720. serializedBone.animation = bone.animations[0].serialize();
  53721. }
  53722. serializationObject.ranges = [];
  53723. for (var name in this._ranges) {
  53724. var range = {};
  53725. range.name = name;
  53726. range.from = this._ranges[name].from;
  53727. range.to = this._ranges[name].to;
  53728. serializationObject.ranges.push(range);
  53729. }
  53730. }
  53731. return serializationObject;
  53732. };
  53733. Skeleton.Parse = function (parsedSkeleton, scene) {
  53734. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  53735. if (parsedSkeleton.dimensionsAtRest) {
  53736. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  53737. }
  53738. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  53739. var index;
  53740. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  53741. var parsedBone = parsedSkeleton.bones[index];
  53742. var parentBone = null;
  53743. if (parsedBone.parentBoneIndex > -1) {
  53744. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  53745. }
  53746. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  53747. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  53748. if (parsedBone.length) {
  53749. bone.length = parsedBone.length;
  53750. }
  53751. if (parsedBone.animation) {
  53752. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  53753. }
  53754. }
  53755. // placed after bones, so createAnimationRange can cascade down
  53756. if (parsedSkeleton.ranges) {
  53757. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  53758. var data = parsedSkeleton.ranges[index];
  53759. skeleton.createAnimationRange(data.name, data.from, data.to);
  53760. }
  53761. }
  53762. return skeleton;
  53763. };
  53764. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  53765. if (forceUpdate === void 0) { forceUpdate = false; }
  53766. var renderId = this._scene.getRenderId();
  53767. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  53768. this.bones[0].computeAbsoluteTransforms();
  53769. this._lastAbsoluteTransformsUpdateId = renderId;
  53770. }
  53771. };
  53772. Skeleton.prototype.getPoseMatrix = function () {
  53773. var poseMatrix;
  53774. if (this._meshesWithPoseMatrix.length > 0) {
  53775. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  53776. }
  53777. return poseMatrix;
  53778. };
  53779. return Skeleton;
  53780. }());
  53781. BABYLON.Skeleton = Skeleton;
  53782. })(BABYLON || (BABYLON = {}));
  53783. //# sourceMappingURL=babylon.skeleton.js.map
  53784. var BABYLON;
  53785. (function (BABYLON) {
  53786. var Internals;
  53787. (function (Internals) {
  53788. var FileFaceOrientation = (function () {
  53789. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  53790. this.name = name;
  53791. this.worldAxisForNormal = worldAxisForNormal;
  53792. this.worldAxisForFileX = worldAxisForFileX;
  53793. this.worldAxisForFileY = worldAxisForFileY;
  53794. }
  53795. return FileFaceOrientation;
  53796. }());
  53797. ;
  53798. /**
  53799. * Helper class dealing with the extraction of spherical polynomial dataArray
  53800. * from a cube map.
  53801. */
  53802. var CubeMapToSphericalPolynomialTools = (function () {
  53803. function CubeMapToSphericalPolynomialTools() {
  53804. }
  53805. /**
  53806. * Converts a cubemap to the according Spherical Polynomial data.
  53807. * This extracts the first 3 orders only as they are the only one used in the lighting.
  53808. *
  53809. * @param cubeInfo The Cube map to extract the information from.
  53810. * @return The Spherical Polynomial data.
  53811. */
  53812. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  53813. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  53814. var totalSolidAngle = 0.0;
  53815. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  53816. var du = 2.0 / cubeInfo.size;
  53817. var dv = du;
  53818. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  53819. var minUV = du * 0.5 - 1.0;
  53820. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  53821. var fileFace = this.FileFaces[faceIndex];
  53822. var dataArray = cubeInfo[fileFace.name];
  53823. var v = minUV;
  53824. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  53825. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  53826. // Because SP is still linear, so summation is fine in that basis.
  53827. for (var y = 0; y < cubeInfo.size; y++) {
  53828. var u = minUV;
  53829. for (var x = 0; x < cubeInfo.size; x++) {
  53830. // World direction (not normalised)
  53831. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  53832. worldDirection.normalize();
  53833. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  53834. if (1) {
  53835. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  53836. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  53837. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  53838. var color = new BABYLON.Color3(r, g, b);
  53839. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53840. }
  53841. else {
  53842. if (faceIndex == 0) {
  53843. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53844. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53845. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53846. }
  53847. else if (faceIndex == 1) {
  53848. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53849. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53850. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53851. }
  53852. else if (faceIndex == 2) {
  53853. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53854. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53855. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53856. }
  53857. else if (faceIndex == 3) {
  53858. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53859. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53860. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  53861. }
  53862. else if (faceIndex == 4) {
  53863. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  53864. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  53865. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53866. }
  53867. else if (faceIndex == 5) {
  53868. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  53869. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  53870. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  53871. }
  53872. 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]);
  53873. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  53874. }
  53875. totalSolidAngle += deltaSolidAngle;
  53876. u += du;
  53877. }
  53878. v += dv;
  53879. }
  53880. }
  53881. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  53882. var correction = correctSolidAngle / totalSolidAngle;
  53883. sphericalHarmonics.scale(correction);
  53884. // Additionally scale by pi -- audit needed
  53885. sphericalHarmonics.scale(1.0 / Math.PI);
  53886. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  53887. };
  53888. return CubeMapToSphericalPolynomialTools;
  53889. }());
  53890. CubeMapToSphericalPolynomialTools.FileFaces = [
  53891. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  53892. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  53893. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  53894. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  53895. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  53896. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  53897. ];
  53898. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  53899. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53900. })(BABYLON || (BABYLON = {}));
  53901. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  53902. var BABYLON;
  53903. (function (BABYLON) {
  53904. var Internals;
  53905. (function (Internals) {
  53906. /**
  53907. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  53908. */
  53909. var PanoramaToCubeMapTools = (function () {
  53910. function PanoramaToCubeMapTools() {
  53911. }
  53912. /**
  53913. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  53914. *
  53915. * @param float32Array The source data.
  53916. * @param inputWidth The width of the input panorama.
  53917. * @param inputhHeight The height of the input panorama.
  53918. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  53919. * @return The cubemap data
  53920. */
  53921. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  53922. if (!float32Array) {
  53923. throw "ConvertPanoramaToCubemap: input cannot be null";
  53924. }
  53925. if (float32Array.length != inputWidth * inputHeight * 3) {
  53926. throw "ConvertPanoramaToCubemap: input size is wrong";
  53927. }
  53928. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  53929. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  53930. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  53931. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  53932. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  53933. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  53934. return {
  53935. front: textureFront,
  53936. back: textureBack,
  53937. left: textureLeft,
  53938. right: textureRight,
  53939. up: textureUp,
  53940. down: textureDown,
  53941. size: size
  53942. };
  53943. };
  53944. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  53945. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  53946. var textureArray = new Float32Array(buffer);
  53947. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  53948. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  53949. var dy = 1 / texSize;
  53950. var fy = 0;
  53951. for (var y = 0; y < texSize; y++) {
  53952. var xv1 = faceData[0];
  53953. var xv2 = faceData[2];
  53954. for (var x = 0; x < texSize; x++) {
  53955. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  53956. v.normalize();
  53957. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  53958. // 3 channels per pixels
  53959. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  53960. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  53961. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  53962. xv1 = xv1.add(rotDX1);
  53963. xv2 = xv2.add(rotDX2);
  53964. }
  53965. fy += dy;
  53966. }
  53967. return textureArray;
  53968. };
  53969. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  53970. var theta = Math.atan2(vDir.z, vDir.x);
  53971. var phi = Math.acos(vDir.y);
  53972. while (theta < -Math.PI)
  53973. theta += 2 * Math.PI;
  53974. while (theta > Math.PI)
  53975. theta -= 2 * Math.PI;
  53976. var dx = theta / Math.PI;
  53977. var dy = phi / Math.PI;
  53978. // recenter.
  53979. dx = dx * 0.5 + 0.5;
  53980. var px = Math.round(dx * inputWidth);
  53981. if (px < 0)
  53982. px = 0;
  53983. else if (px >= inputWidth)
  53984. px = inputWidth - 1;
  53985. var py = Math.round(dy * inputHeight);
  53986. if (py < 0)
  53987. py = 0;
  53988. else if (py >= inputHeight)
  53989. py = inputHeight - 1;
  53990. var inputY = (inputHeight - py - 1);
  53991. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  53992. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  53993. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  53994. return {
  53995. r: r,
  53996. g: g,
  53997. b: b
  53998. };
  53999. };
  54000. return PanoramaToCubeMapTools;
  54001. }());
  54002. PanoramaToCubeMapTools.FACE_FRONT = [
  54003. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54004. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54005. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54006. new BABYLON.Vector3(1.0, 1.0, -1.0)
  54007. ];
  54008. PanoramaToCubeMapTools.FACE_BACK = [
  54009. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54010. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54011. new BABYLON.Vector3(1.0, 1.0, 1.0),
  54012. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  54013. ];
  54014. PanoramaToCubeMapTools.FACE_RIGHT = [
  54015. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54016. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54017. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54018. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54019. ];
  54020. PanoramaToCubeMapTools.FACE_LEFT = [
  54021. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54022. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54023. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54024. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  54025. ];
  54026. PanoramaToCubeMapTools.FACE_DOWN = [
  54027. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54028. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54029. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54030. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54031. ];
  54032. PanoramaToCubeMapTools.FACE_UP = [
  54033. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54034. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54035. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54036. new BABYLON.Vector3(1.0, -1.0, -1.0)
  54037. ];
  54038. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  54039. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54040. })(BABYLON || (BABYLON = {}));
  54041. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  54042. var BABYLON;
  54043. (function (BABYLON) {
  54044. var Internals;
  54045. (function (Internals) {
  54046. ;
  54047. /**
  54048. * This groups tools to convert HDR texture to native colors array.
  54049. */
  54050. var HDRTools = (function () {
  54051. function HDRTools() {
  54052. }
  54053. HDRTools.Ldexp = function (mantissa, exponent) {
  54054. if (exponent > 1023) {
  54055. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  54056. }
  54057. if (exponent < -1074) {
  54058. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  54059. }
  54060. return mantissa * Math.pow(2, exponent);
  54061. };
  54062. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  54063. if (exponent > 0) {
  54064. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  54065. float32array[index + 0] = red * exponent;
  54066. float32array[index + 1] = green * exponent;
  54067. float32array[index + 2] = blue * exponent;
  54068. }
  54069. else {
  54070. float32array[index + 0] = 0;
  54071. float32array[index + 1] = 0;
  54072. float32array[index + 2] = 0;
  54073. }
  54074. };
  54075. HDRTools.readStringLine = function (uint8array, startIndex) {
  54076. var line = "";
  54077. var character = "";
  54078. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  54079. character = String.fromCharCode(uint8array[i]);
  54080. if (character == "\n") {
  54081. break;
  54082. }
  54083. line += character;
  54084. }
  54085. return line;
  54086. };
  54087. /**
  54088. * Reads header information from an RGBE texture stored in a native array.
  54089. * More information on this format are available here:
  54090. * https://en.wikipedia.org/wiki/RGBE_image_format
  54091. *
  54092. * @param uint8array The binary file stored in native array.
  54093. * @return The header information.
  54094. */
  54095. HDRTools.RGBE_ReadHeader = function (uint8array) {
  54096. var height = 0;
  54097. var width = 0;
  54098. var line = this.readStringLine(uint8array, 0);
  54099. if (line[0] != '#' || line[1] != '?') {
  54100. throw "Bad HDR Format.";
  54101. }
  54102. var endOfHeader = false;
  54103. var findFormat = false;
  54104. var lineIndex = 0;
  54105. do {
  54106. lineIndex += (line.length + 1);
  54107. line = this.readStringLine(uint8array, lineIndex);
  54108. if (line == "FORMAT=32-bit_rle_rgbe") {
  54109. findFormat = true;
  54110. }
  54111. else if (line.length == 0) {
  54112. endOfHeader = true;
  54113. }
  54114. } while (!endOfHeader);
  54115. if (!findFormat) {
  54116. throw "HDR Bad header format, unsupported FORMAT";
  54117. }
  54118. lineIndex += (line.length + 1);
  54119. line = this.readStringLine(uint8array, lineIndex);
  54120. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  54121. var match = sizeRegexp.exec(line);
  54122. // TODO. Support +Y and -X if needed.
  54123. if (match.length < 3) {
  54124. throw "HDR Bad header format, no size";
  54125. }
  54126. width = parseInt(match[2]);
  54127. height = parseInt(match[1]);
  54128. if (width < 8 || width > 0x7fff) {
  54129. throw "HDR Bad header format, unsupported size";
  54130. }
  54131. lineIndex += (line.length + 1);
  54132. return {
  54133. height: height,
  54134. width: width,
  54135. dataPosition: lineIndex
  54136. };
  54137. };
  54138. /**
  54139. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  54140. * This RGBE texture needs to store the information as a panorama.
  54141. *
  54142. * More information on this format are available here:
  54143. * https://en.wikipedia.org/wiki/RGBE_image_format
  54144. *
  54145. * @param buffer The binary file stored in an array buffer.
  54146. * @param size The expected size of the extracted cubemap.
  54147. * @return The Cube Map information.
  54148. */
  54149. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  54150. var uint8array = new Uint8Array(buffer);
  54151. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  54152. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54153. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  54154. return cubeMapData;
  54155. };
  54156. /**
  54157. * Returns the pixels data extracted from an RGBE texture.
  54158. * This pixels will be stored left to right up to down in the R G B order in one array.
  54159. *
  54160. * More information on this format are available here:
  54161. * https://en.wikipedia.org/wiki/RGBE_image_format
  54162. *
  54163. * @param uint8array The binary file stored in an array buffer.
  54164. * @param hdrInfo The header information of the file.
  54165. * @return The pixels data in RGB right to left up to down order.
  54166. */
  54167. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  54168. // Keep for multi format supports.
  54169. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54170. };
  54171. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  54172. var num_scanlines = hdrInfo.height;
  54173. var scanline_width = hdrInfo.width;
  54174. var a, b, c, d, count;
  54175. var dataIndex = hdrInfo.dataPosition;
  54176. var index = 0, endIndex = 0, i = 0;
  54177. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  54178. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  54179. // 3 channels of 4 bytes per pixel in float.
  54180. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  54181. var resultArray = new Float32Array(resultBuffer);
  54182. // read in each successive scanline
  54183. while (num_scanlines > 0) {
  54184. a = uint8array[dataIndex++];
  54185. b = uint8array[dataIndex++];
  54186. c = uint8array[dataIndex++];
  54187. d = uint8array[dataIndex++];
  54188. if (a != 2 || b != 2 || (c & 0x80)) {
  54189. // this file is not run length encoded
  54190. throw "HDR Bad header format, not RLE";
  54191. }
  54192. if (((c << 8) | d) != scanline_width) {
  54193. throw "HDR Bad header format, wrong scan line width";
  54194. }
  54195. index = 0;
  54196. // read each of the four channels for the scanline into the buffer
  54197. for (i = 0; i < 4; i++) {
  54198. endIndex = (i + 1) * scanline_width;
  54199. while (index < endIndex) {
  54200. a = uint8array[dataIndex++];
  54201. b = uint8array[dataIndex++];
  54202. if (a > 128) {
  54203. // a run of the same value
  54204. count = a - 128;
  54205. if ((count == 0) || (count > endIndex - index)) {
  54206. throw "HDR Bad Format, bad scanline data (run)";
  54207. }
  54208. while (count-- > 0) {
  54209. scanLineArray[index++] = b;
  54210. }
  54211. }
  54212. else {
  54213. // a non-run
  54214. count = a;
  54215. if ((count == 0) || (count > endIndex - index)) {
  54216. throw "HDR Bad Format, bad scanline data (non-run)";
  54217. }
  54218. scanLineArray[index++] = b;
  54219. if (--count > 0) {
  54220. for (var j = 0; j < count; j++) {
  54221. scanLineArray[index++] = uint8array[dataIndex++];
  54222. }
  54223. }
  54224. }
  54225. }
  54226. }
  54227. // now convert data from buffer into floats
  54228. for (i = 0; i < scanline_width; i++) {
  54229. a = scanLineArray[i];
  54230. b = scanLineArray[i + scanline_width];
  54231. c = scanLineArray[i + 2 * scanline_width];
  54232. d = scanLineArray[i + 3 * scanline_width];
  54233. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  54234. }
  54235. num_scanlines--;
  54236. }
  54237. return resultArray;
  54238. };
  54239. return HDRTools;
  54240. }());
  54241. Internals.HDRTools = HDRTools;
  54242. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54243. })(BABYLON || (BABYLON = {}));
  54244. //# sourceMappingURL=babylon.hdr.js.map
  54245. //_______________________________________________________________
  54246. // Extracted from CubeMapGen:
  54247. // https://code.google.com/archive/p/cubemapgen/
  54248. //
  54249. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54250. //_______________________________________________________________
  54251. var BABYLON;
  54252. (function (BABYLON) {
  54253. var Internals;
  54254. (function (Internals) {
  54255. /**
  54256. * The bounding box information used during the conversion process.
  54257. */
  54258. var CMGBoundinBox = (function () {
  54259. function CMGBoundinBox() {
  54260. this.min = new BABYLON.Vector3(0, 0, 0);
  54261. this.max = new BABYLON.Vector3(0, 0, 0);
  54262. this.clear();
  54263. }
  54264. CMGBoundinBox.prototype.clear = function () {
  54265. this.min.x = CMGBoundinBox.MAX;
  54266. this.min.y = CMGBoundinBox.MAX;
  54267. this.min.z = CMGBoundinBox.MAX;
  54268. this.max.x = CMGBoundinBox.MIN;
  54269. this.max.y = CMGBoundinBox.MIN;
  54270. this.max.z = CMGBoundinBox.MIN;
  54271. };
  54272. CMGBoundinBox.prototype.augment = function (x, y, z) {
  54273. this.min.x = Math.min(this.min.x, x);
  54274. this.min.y = Math.min(this.min.y, y);
  54275. this.min.z = Math.min(this.min.z, z);
  54276. this.max.x = Math.max(this.max.x, x);
  54277. this.max.y = Math.max(this.max.y, y);
  54278. this.max.z = Math.max(this.max.z, z);
  54279. };
  54280. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  54281. this.min.x = Math.max(this.min.x, x);
  54282. this.min.y = Math.max(this.min.y, y);
  54283. this.min.z = Math.max(this.min.z, z);
  54284. };
  54285. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  54286. this.max.x = Math.min(this.max.x, x);
  54287. this.max.y = Math.min(this.max.y, y);
  54288. this.max.z = Math.min(this.max.z, z);
  54289. };
  54290. CMGBoundinBox.prototype.empty = function () {
  54291. if ((this.min.x > this.max.y) ||
  54292. (this.min.y > this.max.y) ||
  54293. (this.min.z > this.max.y)) {
  54294. return true;
  54295. }
  54296. else {
  54297. return false;
  54298. }
  54299. };
  54300. return CMGBoundinBox;
  54301. }());
  54302. CMGBoundinBox.MAX = Number.MAX_VALUE;
  54303. CMGBoundinBox.MIN = Number.MIN_VALUE;
  54304. /**
  54305. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  54306. * required by the glossinees of a material.
  54307. *
  54308. * This only supports the cosine drop power as well as Warp fixup generation method.
  54309. *
  54310. * This is using the process from CubeMapGen described here:
  54311. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54312. */
  54313. var PMREMGenerator = (function () {
  54314. /**
  54315. * Constructor of the generator.
  54316. *
  54317. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  54318. * @param inputSize The size of the cubemap faces
  54319. * @param outputSize The size of the output cubemap faces
  54320. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  54321. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  54322. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  54323. * @param specularPower The max specular level of the desired cubemap
  54324. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  54325. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  54326. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  54327. */
  54328. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  54329. this.input = input;
  54330. this.inputSize = inputSize;
  54331. this.outputSize = outputSize;
  54332. this.maxNumMipLevels = maxNumMipLevels;
  54333. this.numChannels = numChannels;
  54334. this.isFloat = isFloat;
  54335. this.specularPower = specularPower;
  54336. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  54337. this.excludeBase = excludeBase;
  54338. this.fixup = fixup;
  54339. this._outputSurface = [];
  54340. this._numMipLevels = 0;
  54341. }
  54342. /**
  54343. * Launches the filter process and return the result.
  54344. *
  54345. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  54346. */
  54347. PMREMGenerator.prototype.filterCubeMap = function () {
  54348. // Init cubemap processor
  54349. this.init();
  54350. // Filters the cubemap
  54351. this.filterCubeMapMipChain();
  54352. // Returns the filtered mips.
  54353. return this._outputSurface;
  54354. };
  54355. PMREMGenerator.prototype.init = function () {
  54356. var i;
  54357. var j;
  54358. var mipLevelSize;
  54359. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  54360. if (this.maxNumMipLevels == 0) {
  54361. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  54362. }
  54363. //first miplevel size
  54364. mipLevelSize = this.outputSize;
  54365. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  54366. for (j = 0; j < this.maxNumMipLevels; j++) {
  54367. this._outputSurface.length++;
  54368. this._outputSurface[j] = [];
  54369. //Iterate over faces for output images
  54370. for (i = 0; i < 6; i++) {
  54371. this._outputSurface[j].length++;
  54372. // Initializes a new array for the output.
  54373. if (this.isFloat) {
  54374. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54375. }
  54376. else {
  54377. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54378. }
  54379. }
  54380. //next mip level is half size
  54381. mipLevelSize >>= 1;
  54382. this._numMipLevels++;
  54383. //terminate if mip chain becomes too small
  54384. if (mipLevelSize == 0) {
  54385. this.maxNumMipLevels = j;
  54386. return;
  54387. }
  54388. }
  54389. };
  54390. //--------------------------------------------------------------------------------------
  54391. //Cube map filtering and mip chain generation.
  54392. // the cube map filtereing is specified using a number of parameters:
  54393. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  54394. // indicates the region of the hemisphere to filter over for each tap.
  54395. //
  54396. // Note that the top mip level is also a filtered version of the original input images
  54397. // as well in order to create mip chains for diffuse environment illumination.
  54398. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  54399. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  54400. //
  54401. // Then the mip angle used to genreate the next level of the mip chain from the first level
  54402. // is a_InitialMipAngle
  54403. //
  54404. // The angle for the subsequent levels of the mip chain are specified by their parents
  54405. // filtering angle and a per-level scale and bias
  54406. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  54407. //
  54408. //--------------------------------------------------------------------------------------
  54409. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  54410. // First, take count of the lighting model to modify SpecularPower
  54411. // 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;
  54412. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  54413. //Cone angle start (for generating subsequent mip levels)
  54414. var currentSpecularPower = this.specularPower;
  54415. //Build filter lookup tables based on the source miplevel size
  54416. this.precomputeFilterLookupTables(this.inputSize);
  54417. // Note that we need to filter the first level before generating mipmap
  54418. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  54419. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  54420. // TODO : Write a function to copy and scale the base mipmap in output
  54421. // I am just lazy here and just put a high specular power value, and do some if.
  54422. if (this.excludeBase && (levelIndex == 0)) {
  54423. // 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).
  54424. currentSpecularPower = 100000.0;
  54425. }
  54426. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  54427. var srcCubeImage = this.input;
  54428. var dstCubeImage = this._outputSurface[levelIndex];
  54429. var dstSize = this.outputSize >> levelIndex;
  54430. // Compute required angle.
  54431. var angle = this.getBaseFilterAngle(currentSpecularPower);
  54432. // filter cube surfaces
  54433. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  54434. // fix seams
  54435. if (this.fixup) {
  54436. this.fixupCubeEdges(dstCubeImage, dstSize);
  54437. }
  54438. // Decrease the specular power to generate the mipmap chain
  54439. // TODO : Use another method for Exclude (see first comment at start of the function
  54440. if (this.excludeBase && (levelIndex == 0)) {
  54441. currentSpecularPower = this.specularPower;
  54442. }
  54443. currentSpecularPower *= this.cosinePowerDropPerMip;
  54444. }
  54445. };
  54446. //--------------------------------------------------------------------------------------
  54447. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  54448. // It allow to optimize the texel to access base on the specular power.
  54449. //--------------------------------------------------------------------------------------
  54450. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  54451. // We want to find the alpha such that:
  54452. // cos(alpha)^cosinePower = epsilon
  54453. // That's: acos(epsilon^(1/cosinePower))
  54454. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  54455. var angle = 180.0;
  54456. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  54457. angle *= 180.0 / Math.PI; // Convert to degree
  54458. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  54459. return angle;
  54460. };
  54461. //--------------------------------------------------------------------------------------
  54462. //Builds the following lookup tables prior to filtering:
  54463. // -normalizer cube map
  54464. // -tap weight lookup table
  54465. //
  54466. //--------------------------------------------------------------------------------------
  54467. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  54468. var srcTexelAngle;
  54469. var iCubeFace;
  54470. //clear pre-existing normalizer cube map
  54471. this._normCubeMap = [];
  54472. //Normalized vectors per cubeface and per-texel solid angle
  54473. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  54474. };
  54475. //--------------------------------------------------------------------------------------
  54476. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  54477. //
  54478. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  54479. //
  54480. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  54481. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  54482. // below
  54483. //--------------------------------------------------------------------------------------
  54484. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  54485. var iCubeFace;
  54486. var u;
  54487. var v;
  54488. //iterate over cube faces
  54489. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54490. //First three channels for norm cube, and last channel for solid angle
  54491. this._normCubeMap.push(new Float32Array(size * size * 4));
  54492. //fast texture walk, build normalizer cube map
  54493. var facesData = this.input[iCubeFace];
  54494. for (v = 0; v < size; v++) {
  54495. for (u = 0; u < size; u++) {
  54496. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  54497. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  54498. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  54499. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  54500. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  54501. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  54502. }
  54503. }
  54504. }
  54505. };
  54506. //--------------------------------------------------------------------------------------
  54507. // Convert cubemap face texel coordinates and face idx to 3D vector
  54508. // note the U and V coords are integer coords and range from 0 to size-1
  54509. // this routine can be used to generate a normalizer cube map
  54510. //--------------------------------------------------------------------------------------
  54511. // SL BEGIN
  54512. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  54513. var nvcU;
  54514. var nvcV;
  54515. var tempVec;
  54516. // Change from original AMD code
  54517. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54518. // + 0.5f is for texel center addressing
  54519. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  54520. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  54521. // warp fixup
  54522. if (fixup && size > 1) {
  54523. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  54524. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  54525. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  54526. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  54527. }
  54528. // Get current vector
  54529. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  54530. // U contribution
  54531. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54532. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  54533. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  54534. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  54535. // V contribution and Sum
  54536. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54537. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  54538. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  54539. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  54540. //add face axis
  54541. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  54542. PMREMGenerator._vectorTemp.x += faceAxis[0];
  54543. PMREMGenerator._vectorTemp.y += faceAxis[1];
  54544. PMREMGenerator._vectorTemp.z += faceAxis[2];
  54545. //normalize vector
  54546. PMREMGenerator._vectorTemp.normalize();
  54547. return PMREMGenerator._vectorTemp;
  54548. };
  54549. //--------------------------------------------------------------------------------------
  54550. // Convert 3D vector to cubemap face texel coordinates and face idx
  54551. // note the U and V coords are integer coords and range from 0 to size-1
  54552. // this routine can be used to generate a normalizer cube map
  54553. //
  54554. // returns face IDX and texel coords
  54555. //--------------------------------------------------------------------------------------
  54556. // SL BEGIN
  54557. /*
  54558. Mapping Texture Coordinates to Cube Map Faces
  54559. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  54560. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  54561. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  54562. map arrangement in Pixar's RenderMan package.
  54563. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  54564. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  54565. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  54566. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  54567. the major axis direction). The target column in the table below explains how the major axis direction
  54568. maps to the 2D image of a particular cube map target.
  54569. major axis
  54570. direction target sc tc ma
  54571. ---------- --------------------------------- --- --- ---
  54572. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  54573. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  54574. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  54575. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  54576. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  54577. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  54578. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  54579. an updated (s,t) is calculated as follows
  54580. s = ( sc/|ma| + 1 ) / 2
  54581. t = ( tc/|ma| + 1 ) / 2
  54582. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  54583. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  54584. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  54585. */
  54586. // Note this method return U and V in range from 0 to size-1
  54587. // SL END
  54588. // Store the information in vector3 for convenience (faceindex, u, v)
  54589. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  54590. var maxCoord;
  54591. var faceIdx;
  54592. //absolute value 3
  54593. var absX = Math.abs(x);
  54594. var absY = Math.abs(y);
  54595. var absZ = Math.abs(z);
  54596. if (absX >= absY && absX >= absZ) {
  54597. maxCoord = absX;
  54598. if (x >= 0) {
  54599. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  54600. }
  54601. else {
  54602. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54603. }
  54604. }
  54605. else if (absY >= absX && absY >= absZ) {
  54606. maxCoord = absY;
  54607. if (y >= 0) {
  54608. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54609. }
  54610. else {
  54611. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54612. }
  54613. }
  54614. else {
  54615. maxCoord = absZ;
  54616. if (z >= 0) {
  54617. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54618. }
  54619. else {
  54620. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54621. }
  54622. }
  54623. //divide through by max coord so face vector lies on cube face
  54624. var scale = 1 / maxCoord;
  54625. x *= scale;
  54626. y *= scale;
  54627. z *= scale;
  54628. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54629. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  54630. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54631. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  54632. // Modify original AMD code to return value from 0 to Size - 1
  54633. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  54634. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  54635. PMREMGenerator._vectorTemp.x = faceIdx;
  54636. PMREMGenerator._vectorTemp.y = u;
  54637. PMREMGenerator._vectorTemp.z = v;
  54638. return PMREMGenerator._vectorTemp;
  54639. };
  54640. //--------------------------------------------------------------------------------------
  54641. //Original code from Ignacio CastaÒo
  54642. // This formula is from Manne ÷hrstrˆm's thesis.
  54643. // Take two coordiantes in the range [-1, 1] that define a portion of a
  54644. // cube face and return the area of the projection of that portion on the
  54645. // surface of the sphere.
  54646. //--------------------------------------------------------------------------------------
  54647. PMREMGenerator.prototype.areaElement = function (x, y) {
  54648. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  54649. };
  54650. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  54651. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54652. // (+ 0.5f is for texel center addressing)
  54653. u = (2.0 * (u + 0.5) / size) - 1.0;
  54654. v = (2.0 * (v + 0.5) / size) - 1.0;
  54655. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  54656. var invResolution = 1.0 / size;
  54657. // U and V are the -1..1 texture coordinate on the current face.
  54658. // Get projected area for this texel
  54659. var x0 = u - invResolution;
  54660. var y0 = v - invResolution;
  54661. var x1 = u + invResolution;
  54662. var y1 = v + invResolution;
  54663. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  54664. return solidAngle;
  54665. };
  54666. //--------------------------------------------------------------------------------------
  54667. //The key to the speed of these filtering routines is to quickly define a per-face
  54668. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  54669. // Later these pixels are selectively processed based on their dot products to see if
  54670. // they reside within the filtering cone.
  54671. //
  54672. //This is done by computing the smallest per-texel angle to get a conservative estimate
  54673. // of the number of texels needed to be covered in width and height order to filter the
  54674. // region. the bounding box for the center taps face is defined first, and if the
  54675. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  54676. // defined next
  54677. //--------------------------------------------------------------------------------------
  54678. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  54679. // note that pixels within these regions may be rejected
  54680. // based on the anlge
  54681. var iCubeFace;
  54682. var u;
  54683. var v;
  54684. // bounding box per face to specify region to process
  54685. var filterExtents = [];
  54686. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54687. filterExtents.push(new CMGBoundinBox());
  54688. }
  54689. // min angle a src texel can cover (in degrees)
  54690. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  54691. // angle about center tap to define filter cone
  54692. // filter angle is 1/2 the cone angle
  54693. var filterAngle = filterConeAngle / 2.0;
  54694. //ensure filter angle is larger than a texel
  54695. if (filterAngle < srcTexelAngle) {
  54696. filterAngle = srcTexelAngle;
  54697. }
  54698. //ensure filter cone is always smaller than the hemisphere
  54699. if (filterAngle > 90.0) {
  54700. filterAngle = 90.0;
  54701. }
  54702. // the maximum number of texels in 1D the filter cone angle will cover
  54703. // used to determine bounding box size for filter extents
  54704. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  54705. // ensure conservative region always covers at least one texel
  54706. if (filterSize < 1) {
  54707. filterSize = 1;
  54708. }
  54709. // dotProdThresh threshold based on cone angle to determine whether or not taps
  54710. // reside within the cone angle
  54711. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  54712. // process required faces
  54713. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54714. //iterate over dst cube map face texel
  54715. for (v = 0; v < dstSize; v++) {
  54716. for (u = 0; u < dstSize; u++) {
  54717. //get center tap direction
  54718. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  54719. //clear old per-face filter extents
  54720. this.clearFilterExtents(filterExtents);
  54721. //define per-face filter extents
  54722. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  54723. //perform filtering of src faces using filter extents
  54724. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  54725. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  54726. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  54727. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  54728. }
  54729. }
  54730. }
  54731. };
  54732. //--------------------------------------------------------------------------------------
  54733. //Clear filter extents for the 6 cube map faces
  54734. //--------------------------------------------------------------------------------------
  54735. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  54736. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  54737. filterExtents[iCubeFaces].clear();
  54738. }
  54739. };
  54740. //--------------------------------------------------------------------------------------
  54741. //Define per-face bounding box filter extents
  54742. //
  54743. // These define conservative texel regions in each of the faces the filter can possibly
  54744. // process. When the pixels in the regions are actually processed, the dot product
  54745. // between the tap vector and the center tap vector is used to determine the weight of
  54746. // the tap and whether or not the tap is within the cone.
  54747. //
  54748. //--------------------------------------------------------------------------------------
  54749. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  54750. //neighboring face and bleed over amount, and width of BBOX for
  54751. // left, right, top, and bottom edges of this face
  54752. var bleedOverAmount = [0, 0, 0, 0];
  54753. var bleedOverBBoxMin = [0, 0, 0, 0];
  54754. var bleedOverBBoxMax = [0, 0, 0, 0];
  54755. var neighborFace;
  54756. var neighborEdge;
  54757. var oppositeFaceIdx;
  54758. //get face idx, and u, v info from center tap dir
  54759. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  54760. var faceIdx = result.x;
  54761. var u = result.y;
  54762. var v = result.z;
  54763. //define bbox size within face
  54764. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  54765. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  54766. filterExtents[faceIdx].clampMin(0, 0, 0);
  54767. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  54768. //u and v extent in face corresponding to center tap
  54769. var minU = filterExtents[faceIdx].min.x;
  54770. var minV = filterExtents[faceIdx].min.y;
  54771. var maxU = filterExtents[faceIdx].max.x;
  54772. var maxV = filterExtents[faceIdx].max.y;
  54773. //bleed over amounts for face across u=0 edge (left)
  54774. bleedOverAmount[0] = (bboxSize - u);
  54775. bleedOverBBoxMin[0] = minV;
  54776. bleedOverBBoxMax[0] = maxV;
  54777. //bleed over amounts for face across u=1 edge (right)
  54778. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  54779. bleedOverBBoxMin[1] = minV;
  54780. bleedOverBBoxMax[1] = maxV;
  54781. //bleed over to face across v=0 edge (up)
  54782. bleedOverAmount[2] = (bboxSize - v);
  54783. bleedOverBBoxMin[2] = minU;
  54784. bleedOverBBoxMax[2] = maxU;
  54785. //bleed over to face across v=1 edge (down)
  54786. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  54787. bleedOverBBoxMin[3] = minU;
  54788. bleedOverBBoxMax[3] = maxU;
  54789. //compute bleed over regions in neighboring faces
  54790. for (var i = 0; i < 4; i++) {
  54791. if (bleedOverAmount[i] > 0) {
  54792. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  54793. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  54794. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  54795. // be flipped: the cases are
  54796. // if a left edge mates with a left or bottom edge on the neighbor
  54797. // if a top edge mates with a top or right edge on the neighbor
  54798. // if a right edge mates with a right or top edge on the neighbor
  54799. // if a bottom edge mates with a bottom or left edge on the neighbor
  54800. //Seeing as the edges are enumerated as follows
  54801. // left =0
  54802. // right =1
  54803. // top =2
  54804. // bottom =3
  54805. //
  54806. // so if the edge enums are the same, or the sum of the enums == 3,
  54807. // the bbox needs to be flipped
  54808. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  54809. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  54810. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  54811. }
  54812. //The way the bounding box is extended onto the neighboring face
  54813. // depends on which edge of neighboring face abuts with this one
  54814. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  54815. case PMREMGenerator.CP_EDGE_LEFT:
  54816. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  54817. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54818. break;
  54819. case PMREMGenerator.CP_EDGE_RIGHT:
  54820. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  54821. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  54822. break;
  54823. case PMREMGenerator.CP_EDGE_TOP:
  54824. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  54825. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  54826. break;
  54827. case PMREMGenerator.CP_EDGE_BOTTOM:
  54828. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  54829. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  54830. break;
  54831. }
  54832. //clamp filter extents in non-center tap faces to remain within surface
  54833. filterExtents[neighborFace].clampMin(0, 0, 0);
  54834. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  54835. }
  54836. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  54837. // from the center tap face, then process the opposite face entirely for now.
  54838. //Note that the cases in which this happens, what usually happens is that
  54839. // more than one edge bleeds onto the opposite face, and the bounding box
  54840. // encompasses the entire cube map face.
  54841. if (bleedOverAmount[i] > srcSize) {
  54842. //determine opposite face
  54843. switch (faceIdx) {
  54844. case PMREMGenerator.CP_FACE_X_POS:
  54845. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54846. break;
  54847. case PMREMGenerator.CP_FACE_X_NEG:
  54848. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  54849. break;
  54850. case PMREMGenerator.CP_FACE_Y_POS:
  54851. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54852. break;
  54853. case PMREMGenerator.CP_FACE_Y_NEG:
  54854. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54855. break;
  54856. case PMREMGenerator.CP_FACE_Z_POS:
  54857. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54858. break;
  54859. case PMREMGenerator.CP_FACE_Z_NEG:
  54860. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54861. break;
  54862. default:
  54863. break;
  54864. }
  54865. //just encompass entire face for now
  54866. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  54867. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  54868. }
  54869. }
  54870. };
  54871. //--------------------------------------------------------------------------------------
  54872. //ProcessFilterExtents
  54873. // Process bounding box in each cube face
  54874. //
  54875. //--------------------------------------------------------------------------------------
  54876. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  54877. //accumulators are 64-bit floats in order to have the precision needed
  54878. // over a summation of a large number of pixels
  54879. var dstAccum = [0, 0, 0, 0];
  54880. var weightAccum = 0;
  54881. var k = 0;
  54882. var nSrcChannels = this.numChannels;
  54883. // norm cube map and srcCubeMap have same face width
  54884. var faceWidth = srcSize;
  54885. //amount to add to pointer to move to next scanline in images
  54886. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  54887. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  54888. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  54889. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  54890. // iterate over cubefaces
  54891. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  54892. //if bbox is non empty
  54893. if (!filterExtents[iFaceIdx].empty()) {
  54894. var uStart = filterExtents[iFaceIdx].min.x;
  54895. var vStart = filterExtents[iFaceIdx].min.y;
  54896. var uEnd = filterExtents[iFaceIdx].max.x;
  54897. var vEnd = filterExtents[iFaceIdx].max.y;
  54898. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  54899. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  54900. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  54901. for (var v = vStart; v <= vEnd; v++) {
  54902. var normCubeRowWalk = 0;
  54903. var srcCubeRowWalk = 0;
  54904. for (var u = uStart; u <= uEnd; u++) {
  54905. //pointer to direction in cube map associated with texel
  54906. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  54907. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  54908. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  54909. //check dot product to see if texel is within cone
  54910. var tapDotProd = texelVectX * centerTapDir.x +
  54911. texelVectY * centerTapDir.y +
  54912. texelVectZ * centerTapDir.z;
  54913. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  54914. //solid angle stored in 4th channel of normalizer/solid angle cube map
  54915. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  54916. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  54917. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  54918. // so just adding one to specularpower do the trick.
  54919. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  54920. //iterate over channels
  54921. for (k = 0; k < nSrcChannels; k++) {
  54922. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  54923. srcCubeRowWalk++;
  54924. }
  54925. weightAccum += weight; //accumulate weight
  54926. }
  54927. else {
  54928. //step across source pixel
  54929. srcCubeRowWalk += nSrcChannels;
  54930. }
  54931. normCubeRowWalk += 4; // 4 channels per norm cube map.
  54932. }
  54933. startIndexNormCubeMap += normCubePitch;
  54934. startIndexSrcCubeMap += srcCubePitch;
  54935. }
  54936. }
  54937. }
  54938. //divide through by weights if weight is non zero
  54939. if (weightAccum != 0.0) {
  54940. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  54941. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  54942. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  54943. if (this.numChannels > 3) {
  54944. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  54945. }
  54946. }
  54947. else {
  54948. // otherwise sample nearest
  54949. // get face idx and u, v texel coordinate in face
  54950. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  54951. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  54952. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  54953. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  54954. if (this.numChannels > 3) {
  54955. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  54956. }
  54957. }
  54958. return PMREMGenerator._vectorTemp;
  54959. };
  54960. //--------------------------------------------------------------------------------------
  54961. // Fixup cube edges
  54962. //
  54963. // average texels on cube map faces across the edges
  54964. // WARP/BENT Method Only.
  54965. //--------------------------------------------------------------------------------------
  54966. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  54967. var k;
  54968. var j;
  54969. var i;
  54970. var iFace;
  54971. var iCorner = 0;
  54972. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  54973. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  54974. // note that if functionality to filter across the three texels for each corner, then
  54975. //indexed by corner and face idx. the array contains the face the start points belongs to.
  54976. var cornerPtr = [
  54977. [[], [], []],
  54978. [[], [], []],
  54979. [[], [], []],
  54980. [[], [], []],
  54981. [[], [], []],
  54982. [[], [], []],
  54983. [[], [], []],
  54984. [[], [], []]
  54985. ];
  54986. //if there is no fixup, or fixup width = 0, do nothing
  54987. if (cubeMapSize < 1) {
  54988. return;
  54989. }
  54990. //special case 1x1 cubemap, average face colors
  54991. if (cubeMapSize == 1) {
  54992. //iterate over channels
  54993. for (k = 0; k < this.numChannels; k++) {
  54994. var accum = 0.0;
  54995. //iterate over faces to accumulate face colors
  54996. for (iFace = 0; iFace < 6; iFace++) {
  54997. accum += cubeMap[iFace][k];
  54998. }
  54999. //compute average over 6 face colors
  55000. accum /= 6.0;
  55001. //iterate over faces to distribute face colors
  55002. for (iFace = 0; iFace < 6; iFace++) {
  55003. cubeMap[iFace][k] = accum;
  55004. }
  55005. }
  55006. return;
  55007. }
  55008. //iterate over faces to collect list of corner texel pointers
  55009. for (iFace = 0; iFace < 6; iFace++) {
  55010. //the 4 corner pointers for this face
  55011. faceCornerStartIndicies[0] = [iFace, 0];
  55012. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  55013. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  55014. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  55015. //iterate over face corners to collect cube corner pointers
  55016. for (iCorner = 0; iCorner < 4; iCorner++) {
  55017. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  55018. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  55019. cornerNumPtrs[corner]++;
  55020. }
  55021. }
  55022. //iterate over corners to average across corner tap values
  55023. for (iCorner = 0; iCorner < 8; iCorner++) {
  55024. for (k = 0; k < this.numChannels; k++) {
  55025. var cornerTapAccum = 0.0;
  55026. //iterate over corner texels and average results
  55027. for (i = 0; i < 3; i++) {
  55028. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  55029. }
  55030. //divide by 3 to compute average of corner tap values
  55031. cornerTapAccum *= (1.0 / 3.0);
  55032. //iterate over corner texels and average results
  55033. for (i = 0; i < 3; i++) {
  55034. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  55035. }
  55036. }
  55037. }
  55038. //iterate over the twelve edges of the cube to average across edges
  55039. for (i = 0; i < 12; i++) {
  55040. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  55041. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  55042. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  55043. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  55044. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  55045. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  55046. var edgeWalk = 0;
  55047. var neighborEdgeWalk = 0;
  55048. //Determine walking pointers based on edge type
  55049. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  55050. switch (edge) {
  55051. case PMREMGenerator.CP_EDGE_LEFT:
  55052. // no change to faceEdgeStartPtr
  55053. edgeWalk = this.numChannels * cubeMapSize;
  55054. break;
  55055. case PMREMGenerator.CP_EDGE_RIGHT:
  55056. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55057. edgeWalk = this.numChannels * cubeMapSize;
  55058. break;
  55059. case PMREMGenerator.CP_EDGE_TOP:
  55060. // no change to faceEdgeStartPtr
  55061. edgeWalk = this.numChannels;
  55062. break;
  55063. case PMREMGenerator.CP_EDGE_BOTTOM:
  55064. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55065. edgeWalk = this.numChannels;
  55066. break;
  55067. }
  55068. //For certain types of edge abutments, the neighbor edge walk needs to
  55069. // be flipped: the cases are
  55070. // if a left edge mates with a left or bottom edge on the neighbor
  55071. // if a top edge mates with a top or right edge on the neighbor
  55072. // if a right edge mates with a right or top edge on the neighbor
  55073. // if a bottom edge mates with a bottom or left edge on the neighbor
  55074. //Seeing as the edges are enumerated as follows
  55075. // left =0
  55076. // right =1
  55077. // top =2
  55078. // bottom =3
  55079. //
  55080. //If the edge enums are the same, or the sum of the enums == 3,
  55081. // the neighbor edge walk needs to be flipped
  55082. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  55083. switch (neighborEdge) {
  55084. case PMREMGenerator.CP_EDGE_LEFT:
  55085. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  55086. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55087. break;
  55088. case PMREMGenerator.CP_EDGE_RIGHT:
  55089. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55090. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55091. break;
  55092. case PMREMGenerator.CP_EDGE_TOP:
  55093. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55094. neighborEdgeWalk = -this.numChannels;
  55095. break;
  55096. case PMREMGenerator.CP_EDGE_BOTTOM:
  55097. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55098. neighborEdgeWalk = -this.numChannels;
  55099. break;
  55100. }
  55101. }
  55102. else {
  55103. //swapped direction neighbor edge walk
  55104. switch (neighborEdge) {
  55105. case PMREMGenerator.CP_EDGE_LEFT:
  55106. //no change to neighborEdgeStartPtr for this case since it points
  55107. // to the upper left corner already
  55108. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55109. break;
  55110. case PMREMGenerator.CP_EDGE_RIGHT:
  55111. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55112. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55113. break;
  55114. case PMREMGenerator.CP_EDGE_TOP:
  55115. //no change to neighborEdgeStartPtr for this case since it points
  55116. // to the upper left corner already
  55117. neighborEdgeWalk = this.numChannels;
  55118. break;
  55119. case PMREMGenerator.CP_EDGE_BOTTOM:
  55120. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55121. neighborEdgeWalk = this.numChannels;
  55122. break;
  55123. }
  55124. }
  55125. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  55126. //nearby neighborhood
  55127. //step ahead one texel on edge
  55128. edgeStartIndex += edgeWalk;
  55129. neighborEdgeStartIndex += neighborEdgeWalk;
  55130. // note that this loop does not process the corner texels, since they have already been
  55131. // averaged across faces across earlier
  55132. for (j = 1; j < (cubeMapSize - 1); j++) {
  55133. //for each set of taps along edge, average them
  55134. // and rewrite the results into the edges
  55135. for (k = 0; k < this.numChannels; k++) {
  55136. var edgeTap = cubeMap[face][edgeStartIndex + k];
  55137. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  55138. //compute average of tap intensity values
  55139. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  55140. //propagate average of taps to edge taps
  55141. cubeMap[face][edgeStartIndex + k] = avgTap;
  55142. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  55143. }
  55144. edgeStartIndex += edgeWalk;
  55145. neighborEdgeStartIndex += neighborEdgeWalk;
  55146. }
  55147. }
  55148. };
  55149. return PMREMGenerator;
  55150. }());
  55151. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  55152. PMREMGenerator.CP_UDIR = 0;
  55153. PMREMGenerator.CP_VDIR = 1;
  55154. PMREMGenerator.CP_FACEAXIS = 2;
  55155. //used to index cube faces
  55156. PMREMGenerator.CP_FACE_X_POS = 0;
  55157. PMREMGenerator.CP_FACE_X_NEG = 1;
  55158. PMREMGenerator.CP_FACE_Y_POS = 2;
  55159. PMREMGenerator.CP_FACE_Y_NEG = 3;
  55160. PMREMGenerator.CP_FACE_Z_POS = 4;
  55161. PMREMGenerator.CP_FACE_Z_NEG = 5;
  55162. //used to index image edges
  55163. // NOTE.. the actual number corresponding to the edge is important
  55164. // do not change these, or the code will break
  55165. //
  55166. // CP_EDGE_LEFT is u = 0
  55167. // CP_EDGE_RIGHT is u = width-1
  55168. // CP_EDGE_TOP is v = 0
  55169. // CP_EDGE_BOTTOM is v = height-1
  55170. PMREMGenerator.CP_EDGE_LEFT = 0;
  55171. PMREMGenerator.CP_EDGE_RIGHT = 1;
  55172. PMREMGenerator.CP_EDGE_TOP = 2;
  55173. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  55174. //corners of CUBE map (P or N specifys if it corresponds to the
  55175. // positive or negative direction each of X, Y, and Z
  55176. PMREMGenerator.CP_CORNER_NNN = 0;
  55177. PMREMGenerator.CP_CORNER_NNP = 1;
  55178. PMREMGenerator.CP_CORNER_NPN = 2;
  55179. PMREMGenerator.CP_CORNER_NPP = 3;
  55180. PMREMGenerator.CP_CORNER_PNN = 4;
  55181. PMREMGenerator.CP_CORNER_PNP = 5;
  55182. PMREMGenerator.CP_CORNER_PPN = 6;
  55183. PMREMGenerator.CP_CORNER_PPP = 7;
  55184. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  55185. //3x2 matrices that map cube map indexing vectors in 3d
  55186. // (after face selection and divide through by the
  55187. // _ABSOLUTE VALUE_ of the max coord)
  55188. // into NVC space
  55189. //Note this currently assumes the D3D cube face ordering and orientation
  55190. PMREMGenerator._sgFace2DMapping = [
  55191. //XPOS face
  55192. [[0, 0, -1],
  55193. [0, -1, 0],
  55194. [1, 0, 0]],
  55195. //XNEG face
  55196. [[0, 0, 1],
  55197. [0, -1, 0],
  55198. [-1, 0, 0]],
  55199. //YPOS face
  55200. [[1, 0, 0],
  55201. [0, 0, 1],
  55202. [0, 1, 0]],
  55203. //YNEG face
  55204. [[1, 0, 0],
  55205. [0, 0, -1],
  55206. [0, -1, 0]],
  55207. //ZPOS face
  55208. [[1, 0, 0],
  55209. [0, -1, 0],
  55210. [0, 0, 1]],
  55211. //ZNEG face
  55212. [[-1, 0, 0],
  55213. [0, -1, 0],
  55214. [0, 0, -1]],
  55215. ];
  55216. //------------------------------------------------------------------------------
  55217. // D3D cube map face specification
  55218. // mapping from 3D x,y,z cube map lookup coordinates
  55219. // to 2D within face u,v coordinates
  55220. //
  55221. // --------------------> U direction
  55222. // | (within-face texture space)
  55223. // | _____
  55224. // | | |
  55225. // | | +Y |
  55226. // | _____|_____|_____ _____
  55227. // | | | | | |
  55228. // | | -X | +Z | +X | -Z |
  55229. // | |_____|_____|_____|_____|
  55230. // | | |
  55231. // | | -Y |
  55232. // | |_____|
  55233. // |
  55234. // v V direction
  55235. // (within-face texture space)
  55236. //------------------------------------------------------------------------------
  55237. //Information about neighbors and how texture coorrdinates change across faces
  55238. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  55239. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  55240. //Note this currently assumes the D3D cube face ordering and orientation
  55241. PMREMGenerator._sgCubeNgh = [
  55242. //XPOS face
  55243. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55244. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55245. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55246. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  55247. //XNEG face
  55248. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55249. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  55250. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  55251. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  55252. //YPOS face
  55253. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55254. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55255. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55256. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  55257. //YNEG face
  55258. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55259. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55260. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55261. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  55262. //ZPOS face
  55263. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55264. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55265. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55266. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  55267. //ZNEG face
  55268. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55269. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55270. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  55271. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  55272. ];
  55273. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  55274. // this table is used to average over the edges.
  55275. PMREMGenerator._sgCubeEdgeList = [
  55276. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55277. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55278. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55279. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55280. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55281. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55282. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55283. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55284. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  55285. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55286. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55287. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  55288. ];
  55289. //Information about which of the 8 cube corners are correspond to the
  55290. // the 4 corners in each cube face
  55291. // the order is upper left, upper right, lower left, lower right
  55292. PMREMGenerator._sgCubeCornerList = [
  55293. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  55294. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  55295. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  55296. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  55297. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  55298. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  55299. ];
  55300. Internals.PMREMGenerator = PMREMGenerator;
  55301. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55302. })(BABYLON || (BABYLON = {}));
  55303. //# sourceMappingURL=babylon.pmremgenerator.js.map
  55304. var BABYLON;
  55305. (function (BABYLON) {
  55306. /**
  55307. * This represents a texture coming from an HDR input.
  55308. *
  55309. * The only supported format is currently panorama picture stored in RGBE format.
  55310. * Example of such files can be found on HDRLib: http://hdrlib.com/
  55311. */
  55312. var HDRCubeTexture = (function (_super) {
  55313. __extends(HDRCubeTexture, _super);
  55314. /**
  55315. * Instantiates an HDRTexture from the following parameters.
  55316. *
  55317. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  55318. * @param scene The scene the texture will be used in
  55319. * @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.
  55320. * @param noMipmap Forces to not generate the mipmap if true
  55321. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  55322. * @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)
  55323. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  55324. */
  55325. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  55326. if (noMipmap === void 0) { noMipmap = false; }
  55327. if (generateHarmonics === void 0) { generateHarmonics = true; }
  55328. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  55329. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  55330. if (onLoad === void 0) { onLoad = null; }
  55331. if (onError === void 0) { onError = null; }
  55332. var _this = _super.call(this, scene) || this;
  55333. _this._useInGammaSpace = false;
  55334. _this._generateHarmonics = true;
  55335. _this._isBABYLONPreprocessed = false;
  55336. _this._onLoad = null;
  55337. _this._onError = null;
  55338. /**
  55339. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  55340. */
  55341. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55342. /**
  55343. * The spherical polynomial data extracted from the texture.
  55344. */
  55345. _this.sphericalPolynomial = null;
  55346. /**
  55347. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  55348. * This is usefull at run time to apply the good shader.
  55349. */
  55350. _this.isPMREM = false;
  55351. _this._isBlocking = true;
  55352. if (!url) {
  55353. return _this;
  55354. }
  55355. _this.name = url;
  55356. _this.url = url;
  55357. _this.hasAlpha = false;
  55358. _this.isCube = true;
  55359. _this._textureMatrix = BABYLON.Matrix.Identity();
  55360. _this._onLoad = onLoad;
  55361. _this._onError = onError;
  55362. if (size) {
  55363. _this._isBABYLONPreprocessed = false;
  55364. _this._noMipmap = noMipmap;
  55365. _this._size = size;
  55366. _this._useInGammaSpace = useInGammaSpace;
  55367. _this._usePMREMGenerator = usePMREMGenerator &&
  55368. scene.getEngine().getCaps().textureLOD &&
  55369. _this.getScene().getEngine().getCaps().textureFloat &&
  55370. !_this._useInGammaSpace;
  55371. }
  55372. else {
  55373. _this._isBABYLONPreprocessed = true;
  55374. _this._noMipmap = false;
  55375. _this._useInGammaSpace = false;
  55376. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  55377. _this.getScene().getEngine().getCaps().textureFloat &&
  55378. !_this._useInGammaSpace;
  55379. }
  55380. _this.isPMREM = _this._usePMREMGenerator;
  55381. _this._texture = _this._getFromCache(url, _this._noMipmap);
  55382. if (!_this._texture) {
  55383. if (!scene.useDelayedTextureLoading) {
  55384. _this.loadTexture();
  55385. }
  55386. else {
  55387. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55388. }
  55389. }
  55390. return _this;
  55391. }
  55392. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  55393. /**
  55394. * Gets wether or not the texture is blocking during loading.
  55395. */
  55396. get: function () {
  55397. return this._isBlocking;
  55398. },
  55399. /**
  55400. * Sets wether or not the texture is blocking during loading.
  55401. */
  55402. set: function (value) {
  55403. this._isBlocking = value;
  55404. },
  55405. enumerable: true,
  55406. configurable: true
  55407. });
  55408. /**
  55409. * Occurs when the file is a preprocessed .babylon.hdr file.
  55410. */
  55411. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  55412. var _this = this;
  55413. var mipLevels = 0;
  55414. var floatArrayView = null;
  55415. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  55416. var mips = [];
  55417. var startIndex = 30;
  55418. for (var level = 0; level < mipLevels; level++) {
  55419. mips.push([]);
  55420. // Fill each pixel of the mip level.
  55421. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  55422. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55423. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  55424. mips[level].push(faceData);
  55425. startIndex += faceSize;
  55426. }
  55427. }
  55428. return mips;
  55429. } : null;
  55430. var callback = function (buffer) {
  55431. // Create Native Array Views
  55432. var intArrayView = new Int32Array(buffer);
  55433. floatArrayView = new Float32Array(buffer);
  55434. // Fill header.
  55435. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  55436. _this._size = intArrayView[1]; // CubeMap max mip face size.
  55437. // Update Texture Information.
  55438. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  55439. // Fill polynomial information.
  55440. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  55441. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  55442. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  55443. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  55444. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  55445. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  55446. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  55447. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  55448. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  55449. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  55450. // Fill pixel data.
  55451. mipLevels = intArrayView[29]; // Number of mip levels.
  55452. var startIndex = 30;
  55453. var data = [];
  55454. var faceSize = Math.pow(_this._size, 2) * 3;
  55455. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55456. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  55457. startIndex += faceSize;
  55458. }
  55459. var results = [];
  55460. var byteArray = null;
  55461. // Push each faces.
  55462. for (var k = 0; k < 6; k++) {
  55463. var dataFace = null;
  55464. // If special cases.
  55465. if (!mipmapGenerator) {
  55466. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  55467. dataFace = data[j];
  55468. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55469. // 3 channels of 1 bytes per pixel in bytes.
  55470. var byteBuffer = new ArrayBuffer(faceSize);
  55471. byteArray = new Uint8Array(byteBuffer);
  55472. }
  55473. for (var i = 0; i < _this._size * _this._size; i++) {
  55474. // Put in gamma space if requested.
  55475. if (_this._useInGammaSpace) {
  55476. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55477. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55478. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55479. }
  55480. // Convert to int texture for fallback.
  55481. if (byteArray) {
  55482. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55483. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55484. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55485. // May use luminance instead if the result is not accurate.
  55486. var max = Math.max(Math.max(r, g), b);
  55487. if (max > 255) {
  55488. var scale = 255 / max;
  55489. r *= scale;
  55490. g *= scale;
  55491. b *= scale;
  55492. }
  55493. byteArray[(i * 3) + 0] = r;
  55494. byteArray[(i * 3) + 1] = g;
  55495. byteArray[(i * 3) + 2] = b;
  55496. }
  55497. }
  55498. }
  55499. else {
  55500. dataFace = data[k];
  55501. }
  55502. // Fill the array accordingly.
  55503. if (byteArray) {
  55504. results.push(byteArray);
  55505. }
  55506. else {
  55507. results.push(dataFace);
  55508. }
  55509. }
  55510. return results;
  55511. };
  55512. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(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);
  55513. };
  55514. /**
  55515. * Occurs when the file is raw .hdr file.
  55516. */
  55517. HDRCubeTexture.prototype.loadHDRTexture = function () {
  55518. var _this = this;
  55519. var callback = function (buffer) {
  55520. // Extract the raw linear data.
  55521. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  55522. // Generate harmonics if needed.
  55523. if (_this._generateHarmonics) {
  55524. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  55525. }
  55526. var results = [];
  55527. var byteArray = null;
  55528. // Push each faces.
  55529. for (var j = 0; j < 6; j++) {
  55530. // Create uintarray fallback.
  55531. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55532. // 3 channels of 1 bytes per pixel in bytes.
  55533. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  55534. byteArray = new Uint8Array(byteBuffer);
  55535. }
  55536. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  55537. // If special cases.
  55538. if (_this._useInGammaSpace || byteArray) {
  55539. for (var i = 0; i < _this._size * _this._size; i++) {
  55540. // Put in gamma space if requested.
  55541. if (_this._useInGammaSpace) {
  55542. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55543. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55544. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55545. }
  55546. // Convert to int texture for fallback.
  55547. if (byteArray) {
  55548. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55549. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55550. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55551. // May use luminance instead if the result is not accurate.
  55552. var max = Math.max(Math.max(r, g), b);
  55553. if (max > 255) {
  55554. var scale = 255 / max;
  55555. r *= scale;
  55556. g *= scale;
  55557. b *= scale;
  55558. }
  55559. byteArray[(i * 3) + 0] = r;
  55560. byteArray[(i * 3) + 1] = g;
  55561. byteArray[(i * 3) + 2] = b;
  55562. }
  55563. }
  55564. }
  55565. if (byteArray) {
  55566. results.push(byteArray);
  55567. }
  55568. else {
  55569. results.push(dataFace);
  55570. }
  55571. }
  55572. return results;
  55573. };
  55574. var mipmapGenerator = null;
  55575. if (!this._noMipmap &&
  55576. this._usePMREMGenerator) {
  55577. mipmapGenerator = function (data) {
  55578. // Custom setup of the generator matching with the PBR shader values.
  55579. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  55580. return generator.filterCubeMap();
  55581. };
  55582. }
  55583. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(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);
  55584. };
  55585. /**
  55586. * Starts the loading process of the texture.
  55587. */
  55588. HDRCubeTexture.prototype.loadTexture = function () {
  55589. if (this._isBABYLONPreprocessed) {
  55590. this.loadBabylonTexture();
  55591. }
  55592. else {
  55593. this.loadHDRTexture();
  55594. }
  55595. };
  55596. HDRCubeTexture.prototype.clone = function () {
  55597. var size = this._isBABYLONPreprocessed ? null : this._size;
  55598. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  55599. // Base texture
  55600. newTexture.level = this.level;
  55601. newTexture.wrapU = this.wrapU;
  55602. newTexture.wrapV = this.wrapV;
  55603. newTexture.coordinatesIndex = this.coordinatesIndex;
  55604. newTexture.coordinatesMode = this.coordinatesMode;
  55605. return newTexture;
  55606. };
  55607. // Methods
  55608. HDRCubeTexture.prototype.delayLoad = function () {
  55609. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55610. return;
  55611. }
  55612. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55613. this._texture = this._getFromCache(this.url, this._noMipmap);
  55614. if (!this._texture) {
  55615. this.loadTexture();
  55616. }
  55617. };
  55618. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  55619. return this._textureMatrix;
  55620. };
  55621. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55622. var texture = null;
  55623. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55624. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  55625. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  55626. texture.name = parsedTexture.name;
  55627. texture.hasAlpha = parsedTexture.hasAlpha;
  55628. texture.level = parsedTexture.level;
  55629. texture.coordinatesMode = parsedTexture.coordinatesMode;
  55630. texture.isBlocking = parsedTexture.isBlocking;
  55631. }
  55632. return texture;
  55633. };
  55634. HDRCubeTexture.prototype.serialize = function () {
  55635. if (!this.name) {
  55636. return null;
  55637. }
  55638. var serializationObject = {};
  55639. serializationObject.name = this.name;
  55640. serializationObject.hasAlpha = this.hasAlpha;
  55641. serializationObject.isCube = true;
  55642. serializationObject.level = this.level;
  55643. serializationObject.size = this._size;
  55644. serializationObject.coordinatesMode = this.coordinatesMode;
  55645. serializationObject.useInGammaSpace = this._useInGammaSpace;
  55646. serializationObject.generateHarmonics = this._generateHarmonics;
  55647. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  55648. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  55649. serializationObject.customType = "BABYLON.HDRCubeTexture";
  55650. serializationObject.noMipmap = this._noMipmap;
  55651. serializationObject.isBlocking = this._isBlocking;
  55652. return serializationObject;
  55653. };
  55654. /**
  55655. * Saves as a file the data contained in the texture in a binary format.
  55656. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55657. * as the spherical used in the lighting.
  55658. * @param url The HDR file url.
  55659. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55660. * @param onError Method called if any error happens during download.
  55661. * @return The packed binary data.
  55662. */
  55663. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  55664. if (onError === void 0) { onError = null; }
  55665. var callback = function (buffer) {
  55666. var data = new Blob([buffer], { type: 'application/octet-stream' });
  55667. // Returns a URL you can use as a href.
  55668. var objUrl = window.URL.createObjectURL(data);
  55669. // Simulates a link to it and click to dowload.
  55670. var a = document.createElement("a");
  55671. document.body.appendChild(a);
  55672. a.style.display = "none";
  55673. a.href = objUrl;
  55674. a.download = "envmap.babylon.hdr";
  55675. a.click();
  55676. };
  55677. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  55678. };
  55679. /**
  55680. * Serializes the data contained in the texture in a binary format.
  55681. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55682. * as the spherical used in the lighting.
  55683. * @param url The HDR file url.
  55684. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55685. * @param onError Method called if any error happens during download.
  55686. * @return The packed binary data.
  55687. */
  55688. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  55689. if (onError === void 0) { onError = null; }
  55690. // Needs the url tho create the texture.
  55691. if (!url) {
  55692. return null;
  55693. }
  55694. // Check Power of two size.
  55695. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  55696. return null;
  55697. }
  55698. var getDataCallback = function (dataBuffer) {
  55699. // Extract the raw linear data.
  55700. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  55701. // Generate harmonics if needed.
  55702. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  55703. // Generate seamless faces
  55704. var mipGeneratorArray = [];
  55705. // Data are known to be in +X +Y +Z -X -Y -Z
  55706. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  55707. mipGeneratorArray.push(cubeData.right); // +X
  55708. mipGeneratorArray.push(cubeData.left); // -X
  55709. mipGeneratorArray.push(cubeData.up); // +Y
  55710. mipGeneratorArray.push(cubeData.down); // -Y
  55711. mipGeneratorArray.push(cubeData.front); // +Z
  55712. mipGeneratorArray.push(cubeData.back); // -Z
  55713. // Custom setup of the generator matching with the PBR shader values.
  55714. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  55715. var mippedData = generator.filterCubeMap();
  55716. // Compute required byte length.
  55717. var byteLength = 1 * 4; // Raw Data Version int32.
  55718. byteLength += 4; // CubeMap max mip face size int32.
  55719. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  55720. // Add data size.
  55721. byteLength += 4; // Number of mip levels int32.
  55722. for (var level = 0; level < mippedData.length; level++) {
  55723. var mipSize = size >> level;
  55724. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  55725. }
  55726. // Prepare binary structure.
  55727. var buffer = new ArrayBuffer(byteLength);
  55728. var intArrayView = new Int32Array(buffer);
  55729. var floatArrayView = new Float32Array(buffer);
  55730. // Fill header.
  55731. intArrayView[0] = 1; // Version 1.
  55732. intArrayView[1] = size; // CubeMap max mip face size.
  55733. // Fill polynomial information.
  55734. sphericalPolynomial.x.toArray(floatArrayView, 2);
  55735. sphericalPolynomial.y.toArray(floatArrayView, 5);
  55736. sphericalPolynomial.z.toArray(floatArrayView, 8);
  55737. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  55738. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  55739. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  55740. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  55741. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  55742. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  55743. // Fill pixel data.
  55744. intArrayView[29] = mippedData.length; // Number of mip levels.
  55745. var startIndex = 30;
  55746. for (var level = 0; level < mippedData.length; level++) {
  55747. // Fill each pixel of the mip level.
  55748. var faceSize = Math.pow(size >> level, 2) * 3;
  55749. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55750. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  55751. startIndex += faceSize;
  55752. }
  55753. }
  55754. // Callback.
  55755. callback(buffer);
  55756. };
  55757. // Download and process.
  55758. BABYLON.Tools.LoadFile(url, function (data) {
  55759. getDataCallback(data);
  55760. }, null, null, true, onError);
  55761. };
  55762. return HDRCubeTexture;
  55763. }(BABYLON.BaseTexture));
  55764. HDRCubeTexture._facesMapping = [
  55765. "right",
  55766. "up",
  55767. "front",
  55768. "left",
  55769. "down",
  55770. "back"
  55771. ];
  55772. BABYLON.HDRCubeTexture = HDRCubeTexture;
  55773. })(BABYLON || (BABYLON = {}));
  55774. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  55775. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  55776. // Huge respect for a such great lib.
  55777. // Earcut license:
  55778. // Copyright (c) 2016, Mapbox
  55779. //
  55780. // Permission to use, copy, modify, and/or distribute this software for any purpose
  55781. // with or without fee is hereby granted, provided that the above copyright notice
  55782. // and this permission notice appear in all copies.
  55783. //
  55784. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  55785. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  55786. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  55787. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  55788. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  55789. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  55790. // THIS SOFTWARE.
  55791. var Earcut;
  55792. (function (Earcut) {
  55793. /**
  55794. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  55795. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  55796. * @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).
  55797. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  55798. */
  55799. function earcut(data, holeIndices, dim) {
  55800. dim = dim || 2;
  55801. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  55802. if (!outerNode)
  55803. return triangles;
  55804. var minX, minY, maxX, maxY, x, y, size;
  55805. if (hasHoles)
  55806. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  55807. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  55808. if (data.length > 80 * dim) {
  55809. minX = maxX = data[0];
  55810. minY = maxY = data[1];
  55811. for (var i = dim; i < outerLen; i += dim) {
  55812. x = data[i];
  55813. y = data[i + 1];
  55814. if (x < minX)
  55815. minX = x;
  55816. if (y < minY)
  55817. minY = y;
  55818. if (x > maxX)
  55819. maxX = x;
  55820. if (y > maxY)
  55821. maxY = y;
  55822. }
  55823. // minX, minY and size are later used to transform coords into integers for z-order calculation
  55824. size = Math.max(maxX - minX, maxY - minY);
  55825. }
  55826. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  55827. return triangles;
  55828. }
  55829. Earcut.earcut = earcut;
  55830. // create a circular doubly linked list from polygon points in the specified winding order
  55831. function linkedList(data, start, end, dim, clockwise) {
  55832. var i, last;
  55833. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  55834. for (i = start; i < end; i += dim)
  55835. last = insertNode(i, data[i], data[i + 1], last);
  55836. }
  55837. else {
  55838. for (i = end - dim; i >= start; i -= dim)
  55839. last = insertNode(i, data[i], data[i + 1], last);
  55840. }
  55841. if (last && equals(last, last.next)) {
  55842. removeNode(last);
  55843. last = last.next;
  55844. }
  55845. return last;
  55846. }
  55847. // eliminate colinear or duplicate points
  55848. function filterPoints(start, end) {
  55849. if (!start)
  55850. return start;
  55851. if (!end)
  55852. end = start;
  55853. var p = start, again;
  55854. do {
  55855. again = false;
  55856. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  55857. removeNode(p);
  55858. p = end = p.prev;
  55859. if (p === p.next)
  55860. return null;
  55861. again = true;
  55862. }
  55863. else {
  55864. p = p.next;
  55865. }
  55866. } while (again || p !== end);
  55867. return end;
  55868. }
  55869. // main ear slicing loop which triangulates a polygon (given as a linked list)
  55870. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  55871. if (!ear)
  55872. return;
  55873. // interlink polygon nodes in z-order
  55874. if (!pass && size)
  55875. indexCurve(ear, minX, minY, size);
  55876. var stop = ear, prev, next;
  55877. // iterate through ears, slicing them one by one
  55878. while (ear.prev !== ear.next) {
  55879. prev = ear.prev;
  55880. next = ear.next;
  55881. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  55882. // cut off the triangle
  55883. triangles.push(prev.i / dim);
  55884. triangles.push(ear.i / dim);
  55885. triangles.push(next.i / dim);
  55886. removeNode(ear);
  55887. // skipping the next vertice leads to less sliver triangles
  55888. ear = next.next;
  55889. stop = next.next;
  55890. continue;
  55891. }
  55892. ear = next;
  55893. // if we looped through the whole remaining polygon and can't find any more ears
  55894. if (ear === stop) {
  55895. // try filtering points and slicing again
  55896. if (!pass) {
  55897. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  55898. // if this didn't work, try curing all small self-intersections locally
  55899. }
  55900. else if (pass === 1) {
  55901. ear = cureLocalIntersections(ear, triangles, dim);
  55902. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  55903. // as a last resort, try splitting the remaining polygon into two
  55904. }
  55905. else if (pass === 2) {
  55906. splitEarcut(ear, triangles, dim, minX, minY, size);
  55907. }
  55908. break;
  55909. }
  55910. }
  55911. }
  55912. // check whether a polygon node forms a valid ear with adjacent nodes
  55913. function isEar(ear) {
  55914. var a = ear.prev, b = ear, c = ear.next;
  55915. if (area(a, b, c) >= 0)
  55916. return false; // reflex, can't be an ear
  55917. // now make sure we don't have other points inside the potential ear
  55918. var p = ear.next.next;
  55919. while (p !== ear.prev) {
  55920. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55921. area(p.prev, p, p.next) >= 0)
  55922. return false;
  55923. p = p.next;
  55924. }
  55925. return true;
  55926. }
  55927. function isEarHashed(ear, minX, minY, size) {
  55928. var a = ear.prev, b = ear, c = ear.next;
  55929. if (area(a, b, c) >= 0)
  55930. return false; // reflex, can't be an ear
  55931. // triangle bbox; min & max are calculated like this for speed
  55932. 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);
  55933. // z-order range for the current triangle bbox;
  55934. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  55935. // first look for points inside the triangle in increasing z-order
  55936. var p = ear.nextZ;
  55937. while (p && p.z <= maxZ) {
  55938. if (p !== ear.prev &&
  55939. p !== ear.next &&
  55940. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55941. area(p.prev, p, p.next) >= 0)
  55942. return false;
  55943. p = p.nextZ;
  55944. }
  55945. // then look for points in decreasing z-order
  55946. p = ear.prevZ;
  55947. while (p && p.z >= minZ) {
  55948. if (p !== ear.prev &&
  55949. p !== ear.next &&
  55950. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  55951. area(p.prev, p, p.next) >= 0)
  55952. return false;
  55953. p = p.prevZ;
  55954. }
  55955. return true;
  55956. }
  55957. // go through all polygon nodes and cure small local self-intersections
  55958. function cureLocalIntersections(start, triangles, dim) {
  55959. var p = start;
  55960. do {
  55961. var a = p.prev, b = p.next.next;
  55962. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  55963. triangles.push(a.i / dim);
  55964. triangles.push(p.i / dim);
  55965. triangles.push(b.i / dim);
  55966. // remove two nodes involved
  55967. removeNode(p);
  55968. removeNode(p.next);
  55969. p = start = b;
  55970. }
  55971. p = p.next;
  55972. } while (p !== start);
  55973. return p;
  55974. }
  55975. // try splitting polygon into two and triangulate them independently
  55976. function splitEarcut(start, triangles, dim, minX, minY, size) {
  55977. // look for a valid diagonal that divides the polygon into two
  55978. var a = start;
  55979. do {
  55980. var b = a.next.next;
  55981. while (b !== a.prev) {
  55982. if (a.i !== b.i && isValidDiagonal(a, b)) {
  55983. // split the polygon in two by the diagonal
  55984. var c = splitPolygon(a, b);
  55985. // filter colinear points around the cuts
  55986. a = filterPoints(a, a.next);
  55987. c = filterPoints(c, c.next);
  55988. // run earcut on each half
  55989. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  55990. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  55991. return;
  55992. }
  55993. b = b.next;
  55994. }
  55995. a = a.next;
  55996. } while (a !== start);
  55997. }
  55998. // link every hole into the outer loop, producing a single-ring polygon without holes
  55999. function eliminateHoles(data, holeIndices, outerNode, dim) {
  56000. var queue = [], i, len, start, end, list;
  56001. for (i = 0, len = holeIndices.length; i < len; i++) {
  56002. start = holeIndices[i] * dim;
  56003. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  56004. list = linkedList(data, start, end, dim, false);
  56005. if (list === list.next)
  56006. list.steiner = true;
  56007. queue.push(getLeftmost(list));
  56008. }
  56009. queue.sort(compareX);
  56010. // process holes from left to right
  56011. for (i = 0; i < queue.length; i++) {
  56012. eliminateHole(queue[i], outerNode);
  56013. outerNode = filterPoints(outerNode, outerNode.next);
  56014. }
  56015. return outerNode;
  56016. }
  56017. function compareX(a, b) {
  56018. return a.x - b.x;
  56019. }
  56020. // find a bridge between vertices that connects hole with an outer ring and and link it
  56021. function eliminateHole(hole, outerNode) {
  56022. outerNode = findHoleBridge(hole, outerNode);
  56023. if (outerNode) {
  56024. var b = splitPolygon(outerNode, hole);
  56025. filterPoints(b, b.next);
  56026. }
  56027. }
  56028. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  56029. function findHoleBridge(hole, outerNode) {
  56030. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  56031. // find a segment intersected by a ray from the hole's leftmost point to the left;
  56032. // segment's endpoint with lesser x will be potential connection point
  56033. do {
  56034. if (hy <= p.y && hy >= p.next.y) {
  56035. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  56036. if (x <= hx && x > qx) {
  56037. qx = x;
  56038. if (x === hx) {
  56039. if (hy === p.y)
  56040. return p;
  56041. if (hy === p.next.y)
  56042. return p.next;
  56043. }
  56044. m = p.x < p.next.x ? p : p.next;
  56045. }
  56046. }
  56047. p = p.next;
  56048. } while (p !== outerNode);
  56049. if (!m)
  56050. return null;
  56051. if (hx === qx)
  56052. return m.prev; // hole touches outer segment; pick lower endpoint
  56053. // look for points inside the triangle of hole point, segment intersection and endpoint;
  56054. // if there are no points found, we have a valid connection;
  56055. // otherwise choose the point of the minimum angle with the ray as connection point
  56056. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  56057. p = m.next;
  56058. while (p !== stop) {
  56059. if (hx >= p.x &&
  56060. p.x >= mx &&
  56061. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  56062. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  56063. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  56064. m = p;
  56065. tanMin = tan;
  56066. }
  56067. }
  56068. p = p.next;
  56069. }
  56070. return m;
  56071. }
  56072. // interlink polygon nodes in z-order
  56073. function indexCurve(start, minX, minY, size) {
  56074. var p = start;
  56075. do {
  56076. if (p.z === null)
  56077. p.z = zOrder(p.x, p.y, minX, minY, size);
  56078. p.prevZ = p.prev;
  56079. p.nextZ = p.next;
  56080. p = p.next;
  56081. } while (p !== start);
  56082. p.prevZ.nextZ = null;
  56083. p.prevZ = null;
  56084. sortLinked(p);
  56085. }
  56086. // Simon Tatham's linked list merge sort algorithm
  56087. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  56088. function sortLinked(list) {
  56089. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  56090. do {
  56091. p = list;
  56092. list = null;
  56093. tail = null;
  56094. numMerges = 0;
  56095. while (p) {
  56096. numMerges++;
  56097. q = p;
  56098. pSize = 0;
  56099. for (i = 0; i < inSize; i++) {
  56100. pSize++;
  56101. q = q.nextZ;
  56102. if (!q)
  56103. break;
  56104. }
  56105. qSize = inSize;
  56106. while (pSize > 0 || (qSize > 0 && q)) {
  56107. if (pSize === 0) {
  56108. e = q;
  56109. q = q.nextZ;
  56110. qSize--;
  56111. }
  56112. else if (qSize === 0 || !q) {
  56113. e = p;
  56114. p = p.nextZ;
  56115. pSize--;
  56116. }
  56117. else if (p.z <= q.z) {
  56118. e = p;
  56119. p = p.nextZ;
  56120. pSize--;
  56121. }
  56122. else {
  56123. e = q;
  56124. q = q.nextZ;
  56125. qSize--;
  56126. }
  56127. if (tail)
  56128. tail.nextZ = e;
  56129. else
  56130. list = e;
  56131. e.prevZ = tail;
  56132. tail = e;
  56133. }
  56134. p = q;
  56135. }
  56136. tail.nextZ = null;
  56137. inSize *= 2;
  56138. } while (numMerges > 1);
  56139. return list;
  56140. }
  56141. // z-order of a point given coords and size of the data bounding box
  56142. function zOrder(x, y, minX, minY, size) {
  56143. // coords are transformed into non-negative 15-bit integer range
  56144. x = 32767 * (x - minX) / size;
  56145. y = 32767 * (y - minY) / size;
  56146. x = (x | (x << 8)) & 0x00FF00FF;
  56147. x = (x | (x << 4)) & 0x0F0F0F0F;
  56148. x = (x | (x << 2)) & 0x33333333;
  56149. x = (x | (x << 1)) & 0x55555555;
  56150. y = (y | (y << 8)) & 0x00FF00FF;
  56151. y = (y | (y << 4)) & 0x0F0F0F0F;
  56152. y = (y | (y << 2)) & 0x33333333;
  56153. y = (y | (y << 1)) & 0x55555555;
  56154. return x | (y << 1);
  56155. }
  56156. // find the leftmost node of a polygon ring
  56157. function getLeftmost(start) {
  56158. var p = start, leftmost = start;
  56159. do {
  56160. if (p.x < leftmost.x)
  56161. leftmost = p;
  56162. p = p.next;
  56163. } while (p !== start);
  56164. return leftmost;
  56165. }
  56166. // check if a point lies within a convex triangle
  56167. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  56168. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  56169. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  56170. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  56171. }
  56172. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  56173. function isValidDiagonal(a, b) {
  56174. return a.next.i !== b.i &&
  56175. a.prev.i !== b.i &&
  56176. !intersectsPolygon(a, b) &&
  56177. locallyInside(a, b) &&
  56178. locallyInside(b, a) &&
  56179. middleInside(a, b);
  56180. }
  56181. // signed area of a triangle
  56182. function area(p, q, r) {
  56183. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  56184. }
  56185. // check if two points are equal
  56186. function equals(p1, p2) {
  56187. return p1.x === p2.x && p1.y === p2.y;
  56188. }
  56189. // check if two segments intersect
  56190. function intersects(p1, q1, p2, q2) {
  56191. if ((equals(p1, q1) && equals(p2, q2)) ||
  56192. (equals(p1, q2) && equals(p2, q1)))
  56193. return true;
  56194. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  56195. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  56196. }
  56197. // check if a polygon diagonal intersects any polygon segments
  56198. function intersectsPolygon(a, b) {
  56199. var p = a;
  56200. do {
  56201. if (p.i !== a.i &&
  56202. p.next.i !== a.i &&
  56203. p.i !== b.i &&
  56204. p.next.i !== b.i &&
  56205. intersects(p, p.next, a, b))
  56206. return true;
  56207. p = p.next;
  56208. } while (p !== a);
  56209. return false;
  56210. }
  56211. // check if a polygon diagonal is locally inside the polygon
  56212. function locallyInside(a, b) {
  56213. return area(a.prev, a, a.next) < 0
  56214. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  56215. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  56216. }
  56217. // check if the middle point of a polygon diagonal is inside the polygon
  56218. function middleInside(a, b) {
  56219. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  56220. do {
  56221. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  56222. inside = !inside;
  56223. p = p.next;
  56224. } while (p !== a);
  56225. return inside;
  56226. }
  56227. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  56228. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  56229. function splitPolygon(a, b) {
  56230. 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;
  56231. a.next = b;
  56232. b.prev = a;
  56233. a2.next = an;
  56234. an.prev = a2;
  56235. b2.next = a2;
  56236. a2.prev = b2;
  56237. bp.next = b2;
  56238. b2.prev = bp;
  56239. return b2;
  56240. }
  56241. // create a node and optionally link it with previous one (in a circular doubly linked list)
  56242. function insertNode(i, x, y, last) {
  56243. var p = new Node(i, x, y);
  56244. if (!last) {
  56245. p.prev = p;
  56246. p.next = p;
  56247. }
  56248. else {
  56249. p.next = last.next;
  56250. p.prev = last;
  56251. last.next.prev = p;
  56252. last.next = p;
  56253. }
  56254. return p;
  56255. }
  56256. function removeNode(p) {
  56257. p.next.prev = p.prev;
  56258. p.prev.next = p.next;
  56259. if (p.prevZ)
  56260. p.prevZ.nextZ = p.nextZ;
  56261. if (p.nextZ)
  56262. p.nextZ.prevZ = p.prevZ;
  56263. }
  56264. function Node(i, x, y) {
  56265. // vertice index in coordinates array
  56266. this.i = i;
  56267. // vertex coordinates
  56268. this.x = x;
  56269. this.y = y;
  56270. // previous and next vertice nodes in a polygon ring
  56271. this.prev = null;
  56272. this.next = null;
  56273. // z-order curve value
  56274. this.z = null;
  56275. // previous and next nodes in z-order
  56276. this.prevZ = null;
  56277. this.nextZ = null;
  56278. // indicates whether this is a steiner point
  56279. this.steiner = false;
  56280. }
  56281. /**
  56282. * return a percentage difference between the polygon area and its triangulation area;
  56283. * used to verify correctness of triangulation
  56284. */
  56285. function deviation(data, holeIndices, dim, triangles) {
  56286. var hasHoles = holeIndices && holeIndices.length;
  56287. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  56288. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  56289. if (hasHoles) {
  56290. for (var i = 0, len = holeIndices.length; i < len; i++) {
  56291. var start = holeIndices[i] * dim;
  56292. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  56293. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  56294. }
  56295. }
  56296. var trianglesArea = 0;
  56297. for (i = 0; i < triangles.length; i += 3) {
  56298. var a = triangles[i] * dim;
  56299. var b = triangles[i + 1] * dim;
  56300. var c = triangles[i + 2] * dim;
  56301. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  56302. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  56303. }
  56304. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  56305. }
  56306. Earcut.deviation = deviation;
  56307. ;
  56308. function signedArea(data, start, end, dim) {
  56309. var sum = 0;
  56310. for (var i = start, j = end - dim; i < end; i += dim) {
  56311. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  56312. j = i;
  56313. }
  56314. return sum;
  56315. }
  56316. /**
  56317. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  56318. */
  56319. function flatten(data) {
  56320. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  56321. for (var i = 0; i < data.length; i++) {
  56322. for (var j = 0; j < data[i].length; j++) {
  56323. for (var d = 0; d < dim; d++)
  56324. result.vertices.push(data[i][j][d]);
  56325. }
  56326. if (i > 0) {
  56327. holeIndex += data[i - 1].length;
  56328. result.holes.push(holeIndex);
  56329. }
  56330. }
  56331. return result;
  56332. }
  56333. Earcut.flatten = flatten;
  56334. ;
  56335. })(Earcut || (Earcut = {}));
  56336. //# sourceMappingURL=babylon.earcut.js.map
  56337. /// <reference path="..\Math\babylon.math.ts" />
  56338. var BABYLON;
  56339. (function (BABYLON) {
  56340. var IndexedVector2 = (function (_super) {
  56341. __extends(IndexedVector2, _super);
  56342. function IndexedVector2(original, index) {
  56343. var _this = _super.call(this, original.x, original.y) || this;
  56344. _this.index = index;
  56345. return _this;
  56346. }
  56347. return IndexedVector2;
  56348. }(BABYLON.Vector2));
  56349. var PolygonPoints = (function () {
  56350. function PolygonPoints() {
  56351. this.elements = new Array();
  56352. }
  56353. PolygonPoints.prototype.add = function (originalPoints) {
  56354. var _this = this;
  56355. var result = new Array();
  56356. originalPoints.forEach(function (point) {
  56357. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  56358. var newPoint = new IndexedVector2(point, _this.elements.length);
  56359. result.push(newPoint);
  56360. _this.elements.push(newPoint);
  56361. }
  56362. });
  56363. return result;
  56364. };
  56365. PolygonPoints.prototype.computeBounds = function () {
  56366. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  56367. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  56368. this.elements.forEach(function (point) {
  56369. // x
  56370. if (point.x < lmin.x) {
  56371. lmin.x = point.x;
  56372. }
  56373. else if (point.x > lmax.x) {
  56374. lmax.x = point.x;
  56375. }
  56376. // y
  56377. if (point.y < lmin.y) {
  56378. lmin.y = point.y;
  56379. }
  56380. else if (point.y > lmax.y) {
  56381. lmax.y = point.y;
  56382. }
  56383. });
  56384. return {
  56385. min: lmin,
  56386. max: lmax,
  56387. width: lmax.x - lmin.x,
  56388. height: lmax.y - lmin.y
  56389. };
  56390. };
  56391. return PolygonPoints;
  56392. }());
  56393. var Polygon = (function () {
  56394. function Polygon() {
  56395. }
  56396. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  56397. return [
  56398. new BABYLON.Vector2(xmin, ymin),
  56399. new BABYLON.Vector2(xmax, ymin),
  56400. new BABYLON.Vector2(xmax, ymax),
  56401. new BABYLON.Vector2(xmin, ymax)
  56402. ];
  56403. };
  56404. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  56405. if (cx === void 0) { cx = 0; }
  56406. if (cy === void 0) { cy = 0; }
  56407. if (numberOfSides === void 0) { numberOfSides = 32; }
  56408. var result = new Array();
  56409. var angle = 0;
  56410. var increment = (Math.PI * 2) / numberOfSides;
  56411. for (var i = 0; i < numberOfSides; i++) {
  56412. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  56413. angle -= increment;
  56414. }
  56415. return result;
  56416. };
  56417. Polygon.Parse = function (input) {
  56418. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  56419. var i, result = [];
  56420. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  56421. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  56422. }
  56423. return result;
  56424. };
  56425. Polygon.StartingAt = function (x, y) {
  56426. return BABYLON.Path2.StartingAt(x, y);
  56427. };
  56428. return Polygon;
  56429. }());
  56430. BABYLON.Polygon = Polygon;
  56431. var PolygonMeshBuilder = (function () {
  56432. function PolygonMeshBuilder(name, contours, scene) {
  56433. this._points = new PolygonPoints();
  56434. this._outlinepoints = new PolygonPoints();
  56435. this._holes = [];
  56436. this._epoints = new Array();
  56437. this._eholes = new Array();
  56438. this._name = name;
  56439. this._scene = scene;
  56440. var points;
  56441. if (contours instanceof BABYLON.Path2) {
  56442. points = contours.getPoints();
  56443. }
  56444. else {
  56445. points = contours;
  56446. }
  56447. this._addToepoint(points);
  56448. this._points.add(points);
  56449. this._outlinepoints.add(points);
  56450. }
  56451. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  56452. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  56453. var p = points_1[_i];
  56454. this._epoints.push(p.x, p.y);
  56455. }
  56456. };
  56457. PolygonMeshBuilder.prototype.addHole = function (hole) {
  56458. this._points.add(hole);
  56459. var holepoints = new PolygonPoints();
  56460. holepoints.add(hole);
  56461. this._holes.push(holepoints);
  56462. this._eholes.push(this._epoints.length / 2);
  56463. this._addToepoint(hole);
  56464. return this;
  56465. };
  56466. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  56467. var _this = this;
  56468. if (updatable === void 0) { updatable = false; }
  56469. var result = new BABYLON.Mesh(this._name, this._scene);
  56470. var normals = [];
  56471. var positions = [];
  56472. var uvs = [];
  56473. var bounds = this._points.computeBounds();
  56474. this._points.elements.forEach(function (p) {
  56475. normals.push(0, 1.0, 0);
  56476. positions.push(p.x, 0, p.y);
  56477. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  56478. });
  56479. var indices = [];
  56480. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  56481. for (var i = 0; i < res.length; i++) {
  56482. indices.push(res[i]);
  56483. }
  56484. if (depth > 0) {
  56485. var positionscount = (positions.length / 3); //get the current pointcount
  56486. this._points.elements.forEach(function (p) {
  56487. normals.push(0, -1.0, 0);
  56488. positions.push(p.x, -depth, p.y);
  56489. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  56490. });
  56491. var totalCount = indices.length;
  56492. for (var i = 0; i < totalCount; i += 3) {
  56493. var i0 = indices[i + 0];
  56494. var i1 = indices[i + 1];
  56495. var i2 = indices[i + 2];
  56496. indices.push(i2 + positionscount);
  56497. indices.push(i1 + positionscount);
  56498. indices.push(i0 + positionscount);
  56499. }
  56500. //Add the sides
  56501. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  56502. this._holes.forEach(function (hole) {
  56503. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  56504. });
  56505. }
  56506. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  56507. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  56508. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  56509. result.setIndices(indices);
  56510. return result;
  56511. };
  56512. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  56513. var StartIndex = positions.length / 3;
  56514. var ulength = 0;
  56515. for (var i = 0; i < points.elements.length; i++) {
  56516. var p = points.elements[i];
  56517. var p1;
  56518. if ((i + 1) > points.elements.length - 1) {
  56519. p1 = points.elements[0];
  56520. }
  56521. else {
  56522. p1 = points.elements[i + 1];
  56523. }
  56524. positions.push(p.x, 0, p.y);
  56525. positions.push(p.x, -depth, p.y);
  56526. positions.push(p1.x, 0, p1.y);
  56527. positions.push(p1.x, -depth, p1.y);
  56528. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  56529. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  56530. var v3 = v2.subtract(v1);
  56531. var v4 = new BABYLON.Vector3(0, 1, 0);
  56532. var vn = BABYLON.Vector3.Cross(v3, v4);
  56533. vn = vn.normalize();
  56534. uvs.push(ulength / bounds.width, 0);
  56535. uvs.push(ulength / bounds.width, 1);
  56536. ulength += v3.length();
  56537. uvs.push((ulength / bounds.width), 0);
  56538. uvs.push((ulength / bounds.width), 1);
  56539. if (!flip) {
  56540. normals.push(-vn.x, -vn.y, -vn.z);
  56541. normals.push(-vn.x, -vn.y, -vn.z);
  56542. normals.push(-vn.x, -vn.y, -vn.z);
  56543. normals.push(-vn.x, -vn.y, -vn.z);
  56544. indices.push(StartIndex);
  56545. indices.push(StartIndex + 1);
  56546. indices.push(StartIndex + 2);
  56547. indices.push(StartIndex + 1);
  56548. indices.push(StartIndex + 3);
  56549. indices.push(StartIndex + 2);
  56550. }
  56551. else {
  56552. normals.push(vn.x, vn.y, vn.z);
  56553. normals.push(vn.x, vn.y, vn.z);
  56554. normals.push(vn.x, vn.y, vn.z);
  56555. normals.push(vn.x, vn.y, vn.z);
  56556. indices.push(StartIndex);
  56557. indices.push(StartIndex + 2);
  56558. indices.push(StartIndex + 1);
  56559. indices.push(StartIndex + 1);
  56560. indices.push(StartIndex + 2);
  56561. indices.push(StartIndex + 3);
  56562. }
  56563. StartIndex += 4;
  56564. }
  56565. ;
  56566. };
  56567. return PolygonMeshBuilder;
  56568. }());
  56569. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  56570. })(BABYLON || (BABYLON = {}));
  56571. //# sourceMappingURL=babylon.polygonMesh.js.map
  56572. var BABYLON;
  56573. (function (BABYLON) {
  56574. // Unique ID when we import meshes from Babylon to CSG
  56575. var currentCSGMeshId = 0;
  56576. // # class Vertex
  56577. // Represents a vertex of a polygon. Use your own vertex class instead of this
  56578. // one to provide additional features like texture coordinates and vertex
  56579. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  56580. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  56581. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  56582. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  56583. // is not used anywhere else.
  56584. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  56585. var Vertex = (function () {
  56586. function Vertex(pos, normal, uv) {
  56587. this.pos = pos;
  56588. this.normal = normal;
  56589. this.uv = uv;
  56590. }
  56591. Vertex.prototype.clone = function () {
  56592. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  56593. };
  56594. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  56595. // orientation of a polygon is flipped.
  56596. Vertex.prototype.flip = function () {
  56597. this.normal = this.normal.scale(-1);
  56598. };
  56599. // Create a new vertex between this vertex and `other` by linearly
  56600. // interpolating all properties using a parameter of `t`. Subclasses should
  56601. // override this to interpolate additional properties.
  56602. Vertex.prototype.interpolate = function (other, t) {
  56603. 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));
  56604. };
  56605. return Vertex;
  56606. }());
  56607. // # class Plane
  56608. // Represents a plane in 3D space.
  56609. var Plane = (function () {
  56610. function Plane(normal, w) {
  56611. this.normal = normal;
  56612. this.w = w;
  56613. }
  56614. Plane.FromPoints = function (a, b, c) {
  56615. var v0 = c.subtract(a);
  56616. var v1 = b.subtract(a);
  56617. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  56618. return null;
  56619. }
  56620. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  56621. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  56622. };
  56623. Plane.prototype.clone = function () {
  56624. return new Plane(this.normal.clone(), this.w);
  56625. };
  56626. Plane.prototype.flip = function () {
  56627. this.normal.scaleInPlace(-1);
  56628. this.w = -this.w;
  56629. };
  56630. // Split `polygon` by this plane if needed, then put the polygon or polygon
  56631. // fragments in the appropriate lists. Coplanar polygons go into either
  56632. // `coplanarFront` or `coplanarBack` depending on their orientation with
  56633. // respect to this plane. Polygons in front or in back of this plane go into
  56634. // either `front` or `back`.
  56635. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  56636. var COPLANAR = 0;
  56637. var FRONT = 1;
  56638. var BACK = 2;
  56639. var SPANNING = 3;
  56640. // Classify each point as well as the entire polygon into one of the above
  56641. // four classes.
  56642. var polygonType = 0;
  56643. var types = [];
  56644. var i;
  56645. var t;
  56646. for (i = 0; i < polygon.vertices.length; i++) {
  56647. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  56648. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  56649. polygonType |= type;
  56650. types.push(type);
  56651. }
  56652. // Put the polygon in the correct list, splitting it when necessary.
  56653. switch (polygonType) {
  56654. case COPLANAR:
  56655. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  56656. break;
  56657. case FRONT:
  56658. front.push(polygon);
  56659. break;
  56660. case BACK:
  56661. back.push(polygon);
  56662. break;
  56663. case SPANNING:
  56664. var f = [], b = [];
  56665. for (i = 0; i < polygon.vertices.length; i++) {
  56666. var j = (i + 1) % polygon.vertices.length;
  56667. var ti = types[i], tj = types[j];
  56668. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  56669. if (ti !== BACK)
  56670. f.push(vi);
  56671. if (ti !== FRONT)
  56672. b.push(ti !== BACK ? vi.clone() : vi);
  56673. if ((ti | tj) === SPANNING) {
  56674. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  56675. var v = vi.interpolate(vj, t);
  56676. f.push(v);
  56677. b.push(v.clone());
  56678. }
  56679. }
  56680. var poly;
  56681. if (f.length >= 3) {
  56682. poly = new Polygon(f, polygon.shared);
  56683. if (poly.plane)
  56684. front.push(poly);
  56685. }
  56686. if (b.length >= 3) {
  56687. poly = new Polygon(b, polygon.shared);
  56688. if (poly.plane)
  56689. back.push(poly);
  56690. }
  56691. break;
  56692. }
  56693. };
  56694. return Plane;
  56695. }());
  56696. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  56697. // point is on the plane.
  56698. Plane.EPSILON = 1e-5;
  56699. // # class Polygon
  56700. // Represents a convex polygon. The vertices used to initialize a polygon must
  56701. // be coplanar and form a convex loop.
  56702. //
  56703. // Each convex polygon has a `shared` property, which is shared between all
  56704. // polygons that are clones of each other or were split from the same polygon.
  56705. // This can be used to define per-polygon properties (such as surface color).
  56706. var Polygon = (function () {
  56707. function Polygon(vertices, shared) {
  56708. this.vertices = vertices;
  56709. this.shared = shared;
  56710. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  56711. }
  56712. Polygon.prototype.clone = function () {
  56713. var vertices = this.vertices.map(function (v) { return v.clone(); });
  56714. return new Polygon(vertices, this.shared);
  56715. };
  56716. Polygon.prototype.flip = function () {
  56717. this.vertices.reverse().map(function (v) { v.flip(); });
  56718. this.plane.flip();
  56719. };
  56720. return Polygon;
  56721. }());
  56722. // # class Node
  56723. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  56724. // by picking a polygon to split along. That polygon (and all other coplanar
  56725. // polygons) are added directly to that node and the other polygons are added to
  56726. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  56727. // no distinction between internal and leaf nodes.
  56728. var Node = (function () {
  56729. function Node(polygons) {
  56730. this.plane = null;
  56731. this.front = null;
  56732. this.back = null;
  56733. this.polygons = [];
  56734. if (polygons) {
  56735. this.build(polygons);
  56736. }
  56737. }
  56738. Node.prototype.clone = function () {
  56739. var node = new Node();
  56740. node.plane = this.plane && this.plane.clone();
  56741. node.front = this.front && this.front.clone();
  56742. node.back = this.back && this.back.clone();
  56743. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  56744. return node;
  56745. };
  56746. // Convert solid space to empty space and empty space to solid space.
  56747. Node.prototype.invert = function () {
  56748. for (var i = 0; i < this.polygons.length; i++) {
  56749. this.polygons[i].flip();
  56750. }
  56751. if (this.plane) {
  56752. this.plane.flip();
  56753. }
  56754. if (this.front) {
  56755. this.front.invert();
  56756. }
  56757. if (this.back) {
  56758. this.back.invert();
  56759. }
  56760. var temp = this.front;
  56761. this.front = this.back;
  56762. this.back = temp;
  56763. };
  56764. // Recursively remove all polygons in `polygons` that are inside this BSP
  56765. // tree.
  56766. Node.prototype.clipPolygons = function (polygons) {
  56767. if (!this.plane)
  56768. return polygons.slice();
  56769. var front = [], back = [];
  56770. for (var i = 0; i < polygons.length; i++) {
  56771. this.plane.splitPolygon(polygons[i], front, back, front, back);
  56772. }
  56773. if (this.front) {
  56774. front = this.front.clipPolygons(front);
  56775. }
  56776. if (this.back) {
  56777. back = this.back.clipPolygons(back);
  56778. }
  56779. else {
  56780. back = [];
  56781. }
  56782. return front.concat(back);
  56783. };
  56784. // Remove all polygons in this BSP tree that are inside the other BSP tree
  56785. // `bsp`.
  56786. Node.prototype.clipTo = function (bsp) {
  56787. this.polygons = bsp.clipPolygons(this.polygons);
  56788. if (this.front)
  56789. this.front.clipTo(bsp);
  56790. if (this.back)
  56791. this.back.clipTo(bsp);
  56792. };
  56793. // Return a list of all polygons in this BSP tree.
  56794. Node.prototype.allPolygons = function () {
  56795. var polygons = this.polygons.slice();
  56796. if (this.front)
  56797. polygons = polygons.concat(this.front.allPolygons());
  56798. if (this.back)
  56799. polygons = polygons.concat(this.back.allPolygons());
  56800. return polygons;
  56801. };
  56802. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  56803. // new polygons are filtered down to the bottom of the tree and become new
  56804. // nodes there. Each set of polygons is partitioned using the first polygon
  56805. // (no heuristic is used to pick a good split).
  56806. Node.prototype.build = function (polygons) {
  56807. if (!polygons.length)
  56808. return;
  56809. if (!this.plane)
  56810. this.plane = polygons[0].plane.clone();
  56811. var front = [], back = [];
  56812. for (var i = 0; i < polygons.length; i++) {
  56813. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  56814. }
  56815. if (front.length) {
  56816. if (!this.front)
  56817. this.front = new Node();
  56818. this.front.build(front);
  56819. }
  56820. if (back.length) {
  56821. if (!this.back)
  56822. this.back = new Node();
  56823. this.back.build(back);
  56824. }
  56825. };
  56826. return Node;
  56827. }());
  56828. var CSG = (function () {
  56829. function CSG() {
  56830. this.polygons = new Array();
  56831. }
  56832. // Convert BABYLON.Mesh to BABYLON.CSG
  56833. CSG.FromMesh = function (mesh) {
  56834. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  56835. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  56836. if (mesh instanceof BABYLON.Mesh) {
  56837. mesh.computeWorldMatrix(true);
  56838. matrix = mesh.getWorldMatrix();
  56839. meshPosition = mesh.position.clone();
  56840. meshRotation = mesh.rotation.clone();
  56841. if (mesh.rotationQuaternion) {
  56842. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  56843. }
  56844. meshScaling = mesh.scaling.clone();
  56845. }
  56846. else {
  56847. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  56848. }
  56849. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56850. var subMeshes = mesh.subMeshes;
  56851. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  56852. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  56853. vertices = [];
  56854. for (var j = 0; j < 3; j++) {
  56855. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  56856. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  56857. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  56858. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  56859. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  56860. vertex = new Vertex(position, normal, uv);
  56861. vertices.push(vertex);
  56862. }
  56863. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  56864. // To handle the case of degenerated triangle
  56865. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  56866. if (polygon.plane)
  56867. polygons.push(polygon);
  56868. }
  56869. }
  56870. var csg = CSG.FromPolygons(polygons);
  56871. csg.matrix = matrix;
  56872. csg.position = meshPosition;
  56873. csg.rotation = meshRotation;
  56874. csg.scaling = meshScaling;
  56875. csg.rotationQuaternion = meshRotationQuaternion;
  56876. currentCSGMeshId++;
  56877. return csg;
  56878. };
  56879. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  56880. CSG.FromPolygons = function (polygons) {
  56881. var csg = new CSG();
  56882. csg.polygons = polygons;
  56883. return csg;
  56884. };
  56885. CSG.prototype.clone = function () {
  56886. var csg = new CSG();
  56887. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  56888. csg.copyTransformAttributes(this);
  56889. return csg;
  56890. };
  56891. CSG.prototype.toPolygons = function () {
  56892. return this.polygons;
  56893. };
  56894. CSG.prototype.union = function (csg) {
  56895. var a = new Node(this.clone().polygons);
  56896. var b = new Node(csg.clone().polygons);
  56897. a.clipTo(b);
  56898. b.clipTo(a);
  56899. b.invert();
  56900. b.clipTo(a);
  56901. b.invert();
  56902. a.build(b.allPolygons());
  56903. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56904. };
  56905. CSG.prototype.unionInPlace = function (csg) {
  56906. var a = new Node(this.polygons);
  56907. var b = new Node(csg.polygons);
  56908. a.clipTo(b);
  56909. b.clipTo(a);
  56910. b.invert();
  56911. b.clipTo(a);
  56912. b.invert();
  56913. a.build(b.allPolygons());
  56914. this.polygons = a.allPolygons();
  56915. };
  56916. CSG.prototype.subtract = function (csg) {
  56917. var a = new Node(this.clone().polygons);
  56918. var b = new Node(csg.clone().polygons);
  56919. a.invert();
  56920. a.clipTo(b);
  56921. b.clipTo(a);
  56922. b.invert();
  56923. b.clipTo(a);
  56924. b.invert();
  56925. a.build(b.allPolygons());
  56926. a.invert();
  56927. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56928. };
  56929. CSG.prototype.subtractInPlace = function (csg) {
  56930. var a = new Node(this.polygons);
  56931. var b = new Node(csg.polygons);
  56932. a.invert();
  56933. a.clipTo(b);
  56934. b.clipTo(a);
  56935. b.invert();
  56936. b.clipTo(a);
  56937. b.invert();
  56938. a.build(b.allPolygons());
  56939. a.invert();
  56940. this.polygons = a.allPolygons();
  56941. };
  56942. CSG.prototype.intersect = function (csg) {
  56943. var a = new Node(this.clone().polygons);
  56944. var b = new Node(csg.clone().polygons);
  56945. a.invert();
  56946. b.clipTo(a);
  56947. b.invert();
  56948. a.clipTo(b);
  56949. b.clipTo(a);
  56950. a.build(b.allPolygons());
  56951. a.invert();
  56952. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  56953. };
  56954. CSG.prototype.intersectInPlace = function (csg) {
  56955. var a = new Node(this.polygons);
  56956. var b = new Node(csg.polygons);
  56957. a.invert();
  56958. b.clipTo(a);
  56959. b.invert();
  56960. a.clipTo(b);
  56961. b.clipTo(a);
  56962. a.build(b.allPolygons());
  56963. a.invert();
  56964. this.polygons = a.allPolygons();
  56965. };
  56966. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  56967. // not modified.
  56968. CSG.prototype.inverse = function () {
  56969. var csg = this.clone();
  56970. csg.inverseInPlace();
  56971. return csg;
  56972. };
  56973. CSG.prototype.inverseInPlace = function () {
  56974. this.polygons.map(function (p) { p.flip(); });
  56975. };
  56976. // This is used to keep meshes transformations so they can be restored
  56977. // when we build back a Babylon Mesh
  56978. // NB : All CSG operations are performed in world coordinates
  56979. CSG.prototype.copyTransformAttributes = function (csg) {
  56980. this.matrix = csg.matrix;
  56981. this.position = csg.position;
  56982. this.rotation = csg.rotation;
  56983. this.scaling = csg.scaling;
  56984. this.rotationQuaternion = csg.rotationQuaternion;
  56985. return this;
  56986. };
  56987. // Build Raw mesh from CSG
  56988. // Coordinates here are in world space
  56989. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  56990. var matrix = this.matrix.clone();
  56991. matrix.invert();
  56992. 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;
  56993. if (keepSubMeshes) {
  56994. // Sort Polygons, since subMeshes are indices range
  56995. polygons.sort(function (a, b) {
  56996. if (a.shared.meshId === b.shared.meshId) {
  56997. return a.shared.subMeshId - b.shared.subMeshId;
  56998. }
  56999. else {
  57000. return a.shared.meshId - b.shared.meshId;
  57001. }
  57002. });
  57003. }
  57004. for (var i = 0, il = polygons.length; i < il; i++) {
  57005. polygon = polygons[i];
  57006. // Building SubMeshes
  57007. if (!subMesh_dict[polygon.shared.meshId]) {
  57008. subMesh_dict[polygon.shared.meshId] = {};
  57009. }
  57010. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  57011. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  57012. indexStart: +Infinity,
  57013. indexEnd: -Infinity,
  57014. materialIndex: polygon.shared.materialIndex
  57015. };
  57016. }
  57017. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  57018. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  57019. polygonIndices[0] = 0;
  57020. polygonIndices[1] = j - 1;
  57021. polygonIndices[2] = j;
  57022. for (var k = 0; k < 3; k++) {
  57023. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  57024. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  57025. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  57026. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  57027. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  57028. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  57029. // Check if 2 points can be merged
  57030. if (!(typeof vertex_idx !== 'undefined' &&
  57031. normals[vertex_idx * 3] === localNormal.x &&
  57032. normals[vertex_idx * 3 + 1] === localNormal.y &&
  57033. normals[vertex_idx * 3 + 2] === localNormal.z &&
  57034. uvs[vertex_idx * 2] === uv.x &&
  57035. uvs[vertex_idx * 2 + 1] === uv.y)) {
  57036. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  57037. uvs.push(uv.x, uv.y);
  57038. normals.push(normal.x, normal.y, normal.z);
  57039. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  57040. }
  57041. indices.push(vertex_idx);
  57042. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  57043. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  57044. currentIndex++;
  57045. }
  57046. }
  57047. }
  57048. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  57049. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  57050. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  57051. mesh.setIndices(indices);
  57052. if (keepSubMeshes) {
  57053. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  57054. var materialIndexOffset = 0, materialMaxIndex;
  57055. mesh.subMeshes = new Array();
  57056. for (var m in subMesh_dict) {
  57057. materialMaxIndex = -1;
  57058. for (var sm in subMesh_dict[m]) {
  57059. subMesh_obj = subMesh_dict[m][sm];
  57060. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  57061. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  57062. }
  57063. materialIndexOffset += ++materialMaxIndex;
  57064. }
  57065. }
  57066. return mesh;
  57067. };
  57068. // Build Mesh from CSG taking material and transforms into account
  57069. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  57070. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  57071. mesh.material = material;
  57072. mesh.position.copyFrom(this.position);
  57073. mesh.rotation.copyFrom(this.rotation);
  57074. if (this.rotationQuaternion) {
  57075. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  57076. }
  57077. mesh.scaling.copyFrom(this.scaling);
  57078. mesh.computeWorldMatrix(true);
  57079. return mesh;
  57080. };
  57081. return CSG;
  57082. }());
  57083. BABYLON.CSG = CSG;
  57084. })(BABYLON || (BABYLON = {}));
  57085. //# sourceMappingURL=babylon.csg.js.map
  57086. var BABYLON;
  57087. (function (BABYLON) {
  57088. var LensFlare = (function () {
  57089. function LensFlare(size, position, color, imgUrl, system) {
  57090. this.size = size;
  57091. this.position = position;
  57092. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  57093. this.dispose = function () {
  57094. if (this.texture) {
  57095. this.texture.dispose();
  57096. }
  57097. // Remove from scene
  57098. var index = this._system.lensFlares.indexOf(this);
  57099. this._system.lensFlares.splice(index, 1);
  57100. };
  57101. this.color = color || new BABYLON.Color3(1, 1, 1);
  57102. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  57103. this._system = system;
  57104. system.lensFlares.push(this);
  57105. }
  57106. return LensFlare;
  57107. }());
  57108. BABYLON.LensFlare = LensFlare;
  57109. })(BABYLON || (BABYLON = {}));
  57110. //# sourceMappingURL=babylon.lensFlare.js.map
  57111. var BABYLON;
  57112. (function (BABYLON) {
  57113. var LensFlareSystem = (function () {
  57114. function LensFlareSystem(name, emitter, scene) {
  57115. this.name = name;
  57116. this.lensFlares = new Array();
  57117. this.borderLimit = 300;
  57118. this.viewportBorder = 0;
  57119. this.layerMask = 0x0FFFFFFF;
  57120. this._vertexBuffers = {};
  57121. this._isEnabled = true;
  57122. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57123. this._emitter = emitter;
  57124. this.id = name;
  57125. scene.lensFlareSystems.push(this);
  57126. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  57127. var engine = scene.getEngine();
  57128. // VBO
  57129. var vertices = [];
  57130. vertices.push(1, 1);
  57131. vertices.push(-1, 1);
  57132. vertices.push(-1, -1);
  57133. vertices.push(1, -1);
  57134. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57135. // Indices
  57136. var indices = [];
  57137. indices.push(0);
  57138. indices.push(1);
  57139. indices.push(2);
  57140. indices.push(0);
  57141. indices.push(2);
  57142. indices.push(3);
  57143. this._indexBuffer = engine.createIndexBuffer(indices);
  57144. // Effects
  57145. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  57146. }
  57147. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  57148. get: function () {
  57149. return this._isEnabled;
  57150. },
  57151. set: function (value) {
  57152. this._isEnabled = value;
  57153. },
  57154. enumerable: true,
  57155. configurable: true
  57156. });
  57157. LensFlareSystem.prototype.getScene = function () {
  57158. return this._scene;
  57159. };
  57160. LensFlareSystem.prototype.getEmitter = function () {
  57161. return this._emitter;
  57162. };
  57163. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  57164. this._emitter = newEmitter;
  57165. };
  57166. LensFlareSystem.prototype.getEmitterPosition = function () {
  57167. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  57168. };
  57169. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  57170. var position = this.getEmitterPosition();
  57171. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  57172. this._positionX = position.x;
  57173. this._positionY = position.y;
  57174. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  57175. if (this.viewportBorder > 0) {
  57176. globalViewport.x -= this.viewportBorder;
  57177. globalViewport.y -= this.viewportBorder;
  57178. globalViewport.width += this.viewportBorder * 2;
  57179. globalViewport.height += this.viewportBorder * 2;
  57180. position.x += this.viewportBorder;
  57181. position.y += this.viewportBorder;
  57182. this._positionX += this.viewportBorder;
  57183. this._positionY += this.viewportBorder;
  57184. }
  57185. if (position.z > 0) {
  57186. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  57187. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  57188. return true;
  57189. }
  57190. return true;
  57191. }
  57192. return false;
  57193. };
  57194. LensFlareSystem.prototype._isVisible = function () {
  57195. if (!this._isEnabled) {
  57196. return false;
  57197. }
  57198. var emitterPosition = this.getEmitterPosition();
  57199. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  57200. var distance = direction.length();
  57201. direction.normalize();
  57202. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  57203. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  57204. return !pickInfo.hit || pickInfo.distance > distance;
  57205. };
  57206. LensFlareSystem.prototype.render = function () {
  57207. if (!this._effect.isReady())
  57208. return false;
  57209. var engine = this._scene.getEngine();
  57210. var viewport = this._scene.activeCamera.viewport;
  57211. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  57212. // Position
  57213. if (!this.computeEffectivePosition(globalViewport)) {
  57214. return false;
  57215. }
  57216. // Visibility
  57217. if (!this._isVisible()) {
  57218. return false;
  57219. }
  57220. // Intensity
  57221. var awayX;
  57222. var awayY;
  57223. if (this._positionX < this.borderLimit + globalViewport.x) {
  57224. awayX = this.borderLimit + globalViewport.x - this._positionX;
  57225. }
  57226. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  57227. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  57228. }
  57229. else {
  57230. awayX = 0;
  57231. }
  57232. if (this._positionY < this.borderLimit + globalViewport.y) {
  57233. awayY = this.borderLimit + globalViewport.y - this._positionY;
  57234. }
  57235. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  57236. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  57237. }
  57238. else {
  57239. awayY = 0;
  57240. }
  57241. var away = (awayX > awayY) ? awayX : awayY;
  57242. away -= this.viewportBorder;
  57243. if (away > this.borderLimit) {
  57244. away = this.borderLimit;
  57245. }
  57246. var intensity = 1.0 - (away / this.borderLimit);
  57247. if (intensity < 0) {
  57248. return false;
  57249. }
  57250. if (intensity > 1.0) {
  57251. intensity = 1.0;
  57252. }
  57253. if (this.viewportBorder > 0) {
  57254. globalViewport.x += this.viewportBorder;
  57255. globalViewport.y += this.viewportBorder;
  57256. globalViewport.width -= this.viewportBorder * 2;
  57257. globalViewport.height -= this.viewportBorder * 2;
  57258. this._positionX -= this.viewportBorder;
  57259. this._positionY -= this.viewportBorder;
  57260. }
  57261. // Position
  57262. var centerX = globalViewport.x + globalViewport.width / 2;
  57263. var centerY = globalViewport.y + globalViewport.height / 2;
  57264. var distX = centerX - this._positionX;
  57265. var distY = centerY - this._positionY;
  57266. // Effects
  57267. engine.enableEffect(this._effect);
  57268. engine.setState(false);
  57269. engine.setDepthBuffer(false);
  57270. // VBOs
  57271. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57272. // Flares
  57273. for (var index = 0; index < this.lensFlares.length; index++) {
  57274. var flare = this.lensFlares[index];
  57275. engine.setAlphaMode(flare.alphaMode);
  57276. var x = centerX - (distX * flare.position);
  57277. var y = centerY - (distY * flare.position);
  57278. var cw = flare.size;
  57279. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  57280. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  57281. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  57282. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  57283. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  57284. // Texture
  57285. this._effect.setTexture("textureSampler", flare.texture);
  57286. // Color
  57287. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  57288. // Draw order
  57289. engine.draw(true, 0, 6);
  57290. }
  57291. engine.setDepthBuffer(true);
  57292. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57293. return true;
  57294. };
  57295. LensFlareSystem.prototype.dispose = function () {
  57296. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57297. if (vertexBuffer) {
  57298. vertexBuffer.dispose();
  57299. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57300. }
  57301. if (this._indexBuffer) {
  57302. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57303. this._indexBuffer = null;
  57304. }
  57305. while (this.lensFlares.length) {
  57306. this.lensFlares[0].dispose();
  57307. }
  57308. // Remove from scene
  57309. var index = this._scene.lensFlareSystems.indexOf(this);
  57310. this._scene.lensFlareSystems.splice(index, 1);
  57311. };
  57312. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  57313. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  57314. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  57315. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  57316. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  57317. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  57318. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  57319. var parsedFlare = parsedLensFlareSystem.flares[index];
  57320. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  57321. }
  57322. return lensFlareSystem;
  57323. };
  57324. LensFlareSystem.prototype.serialize = function () {
  57325. var serializationObject = {};
  57326. serializationObject.id = this.id;
  57327. serializationObject.name = this.name;
  57328. serializationObject.emitterId = this.getEmitter().id;
  57329. serializationObject.borderLimit = this.borderLimit;
  57330. serializationObject.flares = [];
  57331. for (var index = 0; index < this.lensFlares.length; index++) {
  57332. var flare = this.lensFlares[index];
  57333. serializationObject.flares.push({
  57334. size: flare.size,
  57335. position: flare.position,
  57336. color: flare.color.asArray(),
  57337. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  57338. });
  57339. }
  57340. return serializationObject;
  57341. };
  57342. return LensFlareSystem;
  57343. }());
  57344. BABYLON.LensFlareSystem = LensFlareSystem;
  57345. })(BABYLON || (BABYLON = {}));
  57346. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  57347. var BABYLON;
  57348. (function (BABYLON) {
  57349. /**
  57350. * This is a holder class for the physics joint created by the physics plugin.
  57351. * It holds a set of functions to control the underlying joint.
  57352. */
  57353. var PhysicsJoint = (function () {
  57354. function PhysicsJoint(type, jointData) {
  57355. this.type = type;
  57356. this.jointData = jointData;
  57357. jointData.nativeParams = jointData.nativeParams || {};
  57358. }
  57359. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  57360. get: function () {
  57361. return this._physicsJoint;
  57362. },
  57363. set: function (newJoint) {
  57364. if (this._physicsJoint) {
  57365. //remove from the wolrd
  57366. }
  57367. this._physicsJoint = newJoint;
  57368. },
  57369. enumerable: true,
  57370. configurable: true
  57371. });
  57372. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  57373. set: function (physicsPlugin) {
  57374. this._physicsPlugin = physicsPlugin;
  57375. },
  57376. enumerable: true,
  57377. configurable: true
  57378. });
  57379. /**
  57380. * Execute a function that is physics-plugin specific.
  57381. * @param {Function} func the function that will be executed.
  57382. * It accepts two parameters: the physics world and the physics joint.
  57383. */
  57384. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  57385. func(this._physicsPlugin.world, this._physicsJoint);
  57386. };
  57387. return PhysicsJoint;
  57388. }());
  57389. //TODO check if the native joints are the same
  57390. //Joint Types
  57391. PhysicsJoint.DistanceJoint = 0;
  57392. PhysicsJoint.HingeJoint = 1;
  57393. PhysicsJoint.BallAndSocketJoint = 2;
  57394. PhysicsJoint.WheelJoint = 3;
  57395. PhysicsJoint.SliderJoint = 4;
  57396. //OIMO
  57397. PhysicsJoint.PrismaticJoint = 5;
  57398. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  57399. PhysicsJoint.UniversalJoint = 6;
  57400. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  57401. //Cannon
  57402. //Similar to a Ball-Joint. Different in params
  57403. PhysicsJoint.PointToPointJoint = 8;
  57404. //Cannon only at the moment
  57405. PhysicsJoint.SpringJoint = 9;
  57406. PhysicsJoint.LockJoint = 10;
  57407. BABYLON.PhysicsJoint = PhysicsJoint;
  57408. /**
  57409. * A class representing a physics distance joint.
  57410. */
  57411. var DistanceJoint = (function (_super) {
  57412. __extends(DistanceJoint, _super);
  57413. function DistanceJoint(jointData) {
  57414. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  57415. }
  57416. /**
  57417. * Update the predefined distance.
  57418. */
  57419. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  57420. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  57421. };
  57422. return DistanceJoint;
  57423. }(PhysicsJoint));
  57424. BABYLON.DistanceJoint = DistanceJoint;
  57425. var MotorEnabledJoint = (function (_super) {
  57426. __extends(MotorEnabledJoint, _super);
  57427. function MotorEnabledJoint(type, jointData) {
  57428. return _super.call(this, type, jointData) || this;
  57429. }
  57430. /**
  57431. * Set the motor values.
  57432. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57433. * @param {number} force the force to apply
  57434. * @param {number} maxForce max force for this motor.
  57435. */
  57436. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  57437. this._physicsPlugin.setMotor(this, force, maxForce);
  57438. };
  57439. /**
  57440. * Set the motor's limits.
  57441. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57442. */
  57443. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  57444. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  57445. };
  57446. return MotorEnabledJoint;
  57447. }(PhysicsJoint));
  57448. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  57449. /**
  57450. * This class represents a single hinge physics joint
  57451. */
  57452. var HingeJoint = (function (_super) {
  57453. __extends(HingeJoint, _super);
  57454. function HingeJoint(jointData) {
  57455. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  57456. }
  57457. /**
  57458. * Set the motor values.
  57459. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57460. * @param {number} force the force to apply
  57461. * @param {number} maxForce max force for this motor.
  57462. */
  57463. HingeJoint.prototype.setMotor = function (force, maxForce) {
  57464. this._physicsPlugin.setMotor(this, force, maxForce);
  57465. };
  57466. /**
  57467. * Set the motor's limits.
  57468. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57469. */
  57470. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  57471. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  57472. };
  57473. return HingeJoint;
  57474. }(MotorEnabledJoint));
  57475. BABYLON.HingeJoint = HingeJoint;
  57476. /**
  57477. * This class represents a dual hinge physics joint (same as wheel joint)
  57478. */
  57479. var Hinge2Joint = (function (_super) {
  57480. __extends(Hinge2Joint, _super);
  57481. function Hinge2Joint(jointData) {
  57482. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  57483. }
  57484. /**
  57485. * Set the motor values.
  57486. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57487. * @param {number} force the force to apply
  57488. * @param {number} maxForce max force for this motor.
  57489. * @param {motorIndex} the motor's index, 0 or 1.
  57490. */
  57491. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  57492. if (motorIndex === void 0) { motorIndex = 0; }
  57493. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  57494. };
  57495. /**
  57496. * Set the motor limits.
  57497. * Attention, this function is plugin specific. Engines won't react 100% the same.
  57498. * @param {number} upperLimit the upper limit
  57499. * @param {number} lowerLimit lower limit
  57500. * @param {motorIndex} the motor's index, 0 or 1.
  57501. */
  57502. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  57503. if (motorIndex === void 0) { motorIndex = 0; }
  57504. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  57505. };
  57506. return Hinge2Joint;
  57507. }(MotorEnabledJoint));
  57508. BABYLON.Hinge2Joint = Hinge2Joint;
  57509. })(BABYLON || (BABYLON = {}));
  57510. //# sourceMappingURL=babylon.physicsJoint.js.map
  57511. var BABYLON;
  57512. (function (BABYLON) {
  57513. var PhysicsImpostor = (function () {
  57514. function PhysicsImpostor(object, type, _options, _scene) {
  57515. if (_options === void 0) { _options = { mass: 0 }; }
  57516. var _this = this;
  57517. this.object = object;
  57518. this.type = type;
  57519. this._options = _options;
  57520. this._scene = _scene;
  57521. this._bodyUpdateRequired = false;
  57522. this._onBeforePhysicsStepCallbacks = new Array();
  57523. this._onAfterPhysicsStepCallbacks = new Array();
  57524. this._onPhysicsCollideCallbacks = [];
  57525. this._deltaPosition = BABYLON.Vector3.Zero();
  57526. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  57527. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  57528. /**
  57529. * this function is executed by the physics engine.
  57530. */
  57531. this.beforeStep = function () {
  57532. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  57533. //conjugate deltaRotation
  57534. if (_this._deltaRotationConjugated) {
  57535. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  57536. }
  57537. else {
  57538. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  57539. }
  57540. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  57541. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  57542. func(_this);
  57543. });
  57544. };
  57545. /**
  57546. * this function is executed by the physics engine.
  57547. */
  57548. this.afterStep = function () {
  57549. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  57550. func(_this);
  57551. });
  57552. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  57553. _this.object.position.addInPlace(_this._deltaPosition);
  57554. if (_this._deltaRotation) {
  57555. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  57556. }
  57557. };
  57558. /**
  57559. * Legacy collision detection event support
  57560. */
  57561. this.onCollideEvent = null;
  57562. //event and body object due to cannon's event-based architecture.
  57563. this.onCollide = function (e) {
  57564. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  57565. return;
  57566. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  57567. if (otherImpostor) {
  57568. // Legacy collision detection event support
  57569. if (_this.onCollideEvent) {
  57570. _this.onCollideEvent(_this, otherImpostor);
  57571. }
  57572. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  57573. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  57574. }).forEach(function (obj) {
  57575. obj.callback(_this, otherImpostor);
  57576. });
  57577. }
  57578. };
  57579. //sanity check!
  57580. if (!this.object) {
  57581. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  57582. return;
  57583. }
  57584. //legacy support for old syntax.
  57585. if (!this._scene && object.getScene) {
  57586. this._scene = object.getScene();
  57587. }
  57588. this._physicsEngine = this._scene.getPhysicsEngine();
  57589. if (!this._physicsEngine) {
  57590. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  57591. }
  57592. else {
  57593. //set the object's quaternion, if not set
  57594. if (!this.object.rotationQuaternion) {
  57595. if (this.object.rotation) {
  57596. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  57597. }
  57598. else {
  57599. this.object.rotationQuaternion = new BABYLON.Quaternion();
  57600. }
  57601. }
  57602. //default options params
  57603. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  57604. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  57605. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  57606. this._joints = [];
  57607. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  57608. if (!this.object.parent) {
  57609. this._init();
  57610. }
  57611. else if (this.object.parent.physicsImpostor) {
  57612. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  57613. }
  57614. }
  57615. }
  57616. /**
  57617. * This function will completly initialize this impostor.
  57618. * It will create a new body - but only if this mesh has no parent.
  57619. * If it has, this impostor will not be used other than to define the impostor
  57620. * of the child mesh.
  57621. */
  57622. PhysicsImpostor.prototype._init = function () {
  57623. this._physicsEngine.removeImpostor(this);
  57624. this.physicsBody = null;
  57625. this._parent = this._parent || this._getPhysicsParent();
  57626. if (!this.parent) {
  57627. this._physicsEngine.addImpostor(this);
  57628. }
  57629. };
  57630. PhysicsImpostor.prototype._getPhysicsParent = function () {
  57631. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  57632. var parentMesh = this.object.parent;
  57633. return parentMesh.physicsImpostor;
  57634. }
  57635. return;
  57636. };
  57637. /**
  57638. * Should a new body be generated.
  57639. */
  57640. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  57641. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  57642. };
  57643. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  57644. this.forceUpdate();
  57645. };
  57646. /**
  57647. * Force a regeneration of this or the parent's impostor's body.
  57648. * Use under cautious - This will remove all joints already implemented.
  57649. */
  57650. PhysicsImpostor.prototype.forceUpdate = function () {
  57651. this._init();
  57652. if (this.parent) {
  57653. this.parent.forceUpdate();
  57654. }
  57655. };
  57656. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  57657. /*public get mesh(): AbstractMesh {
  57658. return this._mesh;
  57659. }*/
  57660. /**
  57661. * Gets the body that holds this impostor. Either its own, or its parent.
  57662. */
  57663. get: function () {
  57664. return this._parent ? this._parent.physicsBody : this._physicsBody;
  57665. },
  57666. /**
  57667. * Set the physics body. Used mainly by the physics engine/plugin
  57668. */
  57669. set: function (physicsBody) {
  57670. if (this._physicsBody) {
  57671. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  57672. }
  57673. this._physicsBody = physicsBody;
  57674. this.resetUpdateFlags();
  57675. },
  57676. enumerable: true,
  57677. configurable: true
  57678. });
  57679. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  57680. get: function () {
  57681. return this._parent;
  57682. },
  57683. set: function (value) {
  57684. this._parent = value;
  57685. },
  57686. enumerable: true,
  57687. configurable: true
  57688. });
  57689. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  57690. this._bodyUpdateRequired = false;
  57691. };
  57692. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  57693. if (this.object.getBoundingInfo) {
  57694. var q = this.object.rotationQuaternion;
  57695. //reset rotation
  57696. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  57697. //calculate the world matrix with no rotation
  57698. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  57699. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  57700. //bring back the rotation
  57701. this.object.rotationQuaternion = q;
  57702. //calculate the world matrix with the new rotation
  57703. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  57704. return size;
  57705. }
  57706. else {
  57707. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  57708. }
  57709. };
  57710. PhysicsImpostor.prototype.getObjectCenter = function () {
  57711. if (this.object.getBoundingInfo) {
  57712. return this.object.getBoundingInfo().boundingBox.centerWorld;
  57713. }
  57714. else {
  57715. return this.object.position;
  57716. }
  57717. };
  57718. /**
  57719. * Get a specific parametes from the options parameter.
  57720. */
  57721. PhysicsImpostor.prototype.getParam = function (paramName) {
  57722. return this._options[paramName];
  57723. };
  57724. /**
  57725. * Sets a specific parameter in the options given to the physics plugin
  57726. */
  57727. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  57728. this._options[paramName] = value;
  57729. this._bodyUpdateRequired = true;
  57730. };
  57731. /**
  57732. * Specifically change the body's mass option. Won't recreate the physics body object
  57733. */
  57734. PhysicsImpostor.prototype.setMass = function (mass) {
  57735. if (this.getParam("mass") !== mass) {
  57736. this.setParam("mass", mass);
  57737. }
  57738. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  57739. };
  57740. PhysicsImpostor.prototype.getLinearVelocity = function () {
  57741. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  57742. };
  57743. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  57744. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  57745. };
  57746. PhysicsImpostor.prototype.getAngularVelocity = function () {
  57747. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  57748. };
  57749. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  57750. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  57751. };
  57752. /**
  57753. * Execute a function with the physics plugin native code.
  57754. * Provide a function the will have two variables - the world object and the physics body object.
  57755. */
  57756. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  57757. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  57758. };
  57759. /**
  57760. * Register a function that will be executed before the physics world is stepping forward.
  57761. */
  57762. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  57763. this._onBeforePhysicsStepCallbacks.push(func);
  57764. };
  57765. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  57766. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  57767. if (index > -1) {
  57768. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  57769. }
  57770. else {
  57771. BABYLON.Tools.Warn("Function to remove was not found");
  57772. }
  57773. };
  57774. /**
  57775. * Register a function that will be executed after the physics step
  57776. */
  57777. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  57778. this._onAfterPhysicsStepCallbacks.push(func);
  57779. };
  57780. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  57781. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  57782. if (index > -1) {
  57783. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  57784. }
  57785. else {
  57786. BABYLON.Tools.Warn("Function to remove was not found");
  57787. }
  57788. };
  57789. /**
  57790. * register a function that will be executed when this impostor collides against a different body.
  57791. */
  57792. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  57793. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  57794. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  57795. };
  57796. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  57797. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  57798. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  57799. if (index > -1) {
  57800. this._onPhysicsCollideCallbacks.splice(index, 1);
  57801. }
  57802. else {
  57803. BABYLON.Tools.Warn("Function to remove was not found");
  57804. }
  57805. };
  57806. /**
  57807. * Apply a force
  57808. */
  57809. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  57810. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  57811. };
  57812. /**
  57813. * Apply an impulse
  57814. */
  57815. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  57816. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  57817. };
  57818. /**
  57819. * A help function to create a joint.
  57820. */
  57821. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  57822. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  57823. this.addJoint(otherImpostor, joint);
  57824. };
  57825. /**
  57826. * Add a joint to this impostor with a different impostor.
  57827. */
  57828. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  57829. this._joints.push({
  57830. otherImpostor: otherImpostor,
  57831. joint: joint
  57832. });
  57833. this._physicsEngine.addJoint(this, otherImpostor, joint);
  57834. };
  57835. /**
  57836. * Will keep this body still, in a sleep mode.
  57837. */
  57838. PhysicsImpostor.prototype.sleep = function () {
  57839. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  57840. };
  57841. /**
  57842. * Wake the body up.
  57843. */
  57844. PhysicsImpostor.prototype.wakeUp = function () {
  57845. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  57846. };
  57847. PhysicsImpostor.prototype.clone = function (newObject) {
  57848. if (!newObject)
  57849. return null;
  57850. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  57851. };
  57852. PhysicsImpostor.prototype.dispose = function () {
  57853. var _this = this;
  57854. //no dispose if no physics engine is available.
  57855. if (!this._physicsEngine) {
  57856. return;
  57857. }
  57858. this._joints.forEach(function (j) {
  57859. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  57860. });
  57861. //dispose the physics body
  57862. this._physicsEngine.removeImpostor(this);
  57863. if (this.parent) {
  57864. this.parent.forceUpdate();
  57865. }
  57866. else {
  57867. /*this._object.getChildMeshes().forEach(function(mesh) {
  57868. if (mesh.physicsImpostor) {
  57869. if (disposeChildren) {
  57870. mesh.physicsImpostor.dispose();
  57871. mesh.physicsImpostor = null;
  57872. }
  57873. }
  57874. })*/
  57875. }
  57876. };
  57877. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  57878. this._deltaPosition.copyFrom(position);
  57879. };
  57880. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  57881. if (!this._deltaRotation) {
  57882. this._deltaRotation = new BABYLON.Quaternion();
  57883. }
  57884. this._deltaRotation.copyFrom(rotation);
  57885. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  57886. };
  57887. return PhysicsImpostor;
  57888. }());
  57889. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  57890. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  57891. //Impostor types
  57892. PhysicsImpostor.NoImpostor = 0;
  57893. PhysicsImpostor.SphereImpostor = 1;
  57894. PhysicsImpostor.BoxImpostor = 2;
  57895. PhysicsImpostor.PlaneImpostor = 3;
  57896. PhysicsImpostor.MeshImpostor = 4;
  57897. PhysicsImpostor.CylinderImpostor = 7;
  57898. PhysicsImpostor.ParticleImpostor = 8;
  57899. PhysicsImpostor.HeightmapImpostor = 9;
  57900. BABYLON.PhysicsImpostor = PhysicsImpostor;
  57901. })(BABYLON || (BABYLON = {}));
  57902. //# sourceMappingURL=babylon.physicsImpostor.js.map
  57903. var BABYLON;
  57904. (function (BABYLON) {
  57905. var PhysicsEngine = (function () {
  57906. function PhysicsEngine(gravity, _physicsPlugin) {
  57907. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  57908. this._physicsPlugin = _physicsPlugin;
  57909. //new methods and parameters
  57910. this._impostors = [];
  57911. this._joints = [];
  57912. if (!this._physicsPlugin.isSupported()) {
  57913. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  57914. + "Please make sure it is included.");
  57915. }
  57916. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  57917. this.setGravity(gravity);
  57918. this.setTimeStep();
  57919. }
  57920. PhysicsEngine.prototype.setGravity = function (gravity) {
  57921. this.gravity = gravity;
  57922. this._physicsPlugin.setGravity(this.gravity);
  57923. };
  57924. /**
  57925. * Set the time step of the physics engine.
  57926. * default is 1/60.
  57927. * To slow it down, enter 1/600 for example.
  57928. * To speed it up, 1/30
  57929. * @param {number} newTimeStep the new timestep to apply to this world.
  57930. */
  57931. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  57932. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  57933. this._physicsPlugin.setTimeStep(newTimeStep);
  57934. };
  57935. PhysicsEngine.prototype.dispose = function () {
  57936. this._impostors.forEach(function (impostor) {
  57937. impostor.dispose();
  57938. });
  57939. this._physicsPlugin.dispose();
  57940. };
  57941. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  57942. return this._physicsPlugin.name;
  57943. };
  57944. /**
  57945. * Adding a new impostor for the impostor tracking.
  57946. * This will be done by the impostor itself.
  57947. * @param {PhysicsImpostor} impostor the impostor to add
  57948. */
  57949. PhysicsEngine.prototype.addImpostor = function (impostor) {
  57950. impostor.uniqueId = this._impostors.push(impostor);
  57951. //if no parent, generate the body
  57952. if (!impostor.parent) {
  57953. this._physicsPlugin.generatePhysicsBody(impostor);
  57954. }
  57955. };
  57956. /**
  57957. * Remove an impostor from the engine.
  57958. * This impostor and its mesh will not longer be updated by the physics engine.
  57959. * @param {PhysicsImpostor} impostor the impostor to remove
  57960. */
  57961. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  57962. var index = this._impostors.indexOf(impostor);
  57963. if (index > -1) {
  57964. var removed = this._impostors.splice(index, 1);
  57965. //Is it needed?
  57966. if (removed.length) {
  57967. //this will also remove it from the world.
  57968. removed[0].physicsBody = null;
  57969. }
  57970. }
  57971. };
  57972. /**
  57973. * Add a joint to the physics engine
  57974. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  57975. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  57976. * @param {PhysicsJoint} the joint that will connect both impostors.
  57977. */
  57978. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  57979. var impostorJoint = {
  57980. mainImpostor: mainImpostor,
  57981. connectedImpostor: connectedImpostor,
  57982. joint: joint
  57983. };
  57984. joint.physicsPlugin = this._physicsPlugin;
  57985. this._joints.push(impostorJoint);
  57986. this._physicsPlugin.generateJoint(impostorJoint);
  57987. };
  57988. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  57989. var matchingJoints = this._joints.filter(function (impostorJoint) {
  57990. return (impostorJoint.connectedImpostor === connectedImpostor
  57991. && impostorJoint.joint === joint
  57992. && impostorJoint.mainImpostor === mainImpostor);
  57993. });
  57994. if (matchingJoints.length) {
  57995. this._physicsPlugin.removeJoint(matchingJoints[0]);
  57996. //TODO remove it from the list as well
  57997. }
  57998. };
  57999. /**
  58000. * Called by the scene. no need to call it.
  58001. */
  58002. PhysicsEngine.prototype._step = function (delta) {
  58003. var _this = this;
  58004. //check if any mesh has no body / requires an update
  58005. this._impostors.forEach(function (impostor) {
  58006. if (impostor.isBodyInitRequired()) {
  58007. _this._physicsPlugin.generatePhysicsBody(impostor);
  58008. }
  58009. });
  58010. if (delta > 0.1) {
  58011. delta = 0.1;
  58012. }
  58013. else if (delta <= 0) {
  58014. delta = 1.0 / 60.0;
  58015. }
  58016. this._physicsPlugin.executeStep(delta, this._impostors);
  58017. };
  58018. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  58019. return this._physicsPlugin;
  58020. };
  58021. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  58022. for (var i = 0; i < this._impostors.length; ++i) {
  58023. if (this._impostors[i].object === object) {
  58024. return this._impostors[i];
  58025. }
  58026. }
  58027. };
  58028. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  58029. for (var i = 0; i < this._impostors.length; ++i) {
  58030. if (this._impostors[i].physicsBody === body) {
  58031. return this._impostors[i];
  58032. }
  58033. }
  58034. };
  58035. return PhysicsEngine;
  58036. }());
  58037. // Statics
  58038. PhysicsEngine.Epsilon = 0.001;
  58039. BABYLON.PhysicsEngine = PhysicsEngine;
  58040. })(BABYLON || (BABYLON = {}));
  58041. //# sourceMappingURL=babylon.physicsEngine.js.map
  58042. var BABYLON;
  58043. (function (BABYLON) {
  58044. var CannonJSPlugin = (function () {
  58045. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  58046. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  58047. if (iterations === void 0) { iterations = 10; }
  58048. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  58049. this.name = "CannonJSPlugin";
  58050. this._physicsMaterials = [];
  58051. this._fixedTimeStep = 1 / 60;
  58052. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  58053. this._currentCollisionGroup = 2;
  58054. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  58055. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  58056. this._tmpPosition = BABYLON.Vector3.Zero();
  58057. this._tmpQuaternion = new BABYLON.Quaternion();
  58058. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  58059. this._tmpDeltaRotation = new BABYLON.Quaternion();
  58060. this._tmpUnityRotation = new BABYLON.Quaternion();
  58061. if (!this.isSupported()) {
  58062. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  58063. return;
  58064. }
  58065. this.world = new CANNON.World();
  58066. this.world.broadphase = new CANNON.NaiveBroadphase();
  58067. this.world.solver.iterations = iterations;
  58068. }
  58069. CannonJSPlugin.prototype.setGravity = function (gravity) {
  58070. this.world.gravity.copy(gravity);
  58071. };
  58072. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  58073. this._fixedTimeStep = timeStep;
  58074. };
  58075. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  58076. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  58077. };
  58078. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  58079. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  58080. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  58081. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  58082. };
  58083. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  58084. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  58085. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  58086. impostor.physicsBody.applyForce(impulse, worldPoint);
  58087. };
  58088. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  58089. //parent-child relationship. Does this impostor has a parent impostor?
  58090. if (impostor.parent) {
  58091. if (impostor.physicsBody) {
  58092. this.removePhysicsBody(impostor);
  58093. //TODO is that needed?
  58094. impostor.forceUpdate();
  58095. }
  58096. return;
  58097. }
  58098. //should a new body be created for this impostor?
  58099. if (impostor.isBodyInitRequired()) {
  58100. var shape = this._createShape(impostor);
  58101. //unregister events, if body is being changed
  58102. var oldBody = impostor.physicsBody;
  58103. if (oldBody) {
  58104. this.removePhysicsBody(impostor);
  58105. }
  58106. //create the body and material
  58107. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  58108. var bodyCreationObject = {
  58109. mass: impostor.getParam("mass"),
  58110. material: material
  58111. };
  58112. // A simple extend, in case native options were used.
  58113. var nativeOptions = impostor.getParam("nativeOptions");
  58114. for (var key in nativeOptions) {
  58115. if (nativeOptions.hasOwnProperty(key)) {
  58116. bodyCreationObject[key] = nativeOptions[key];
  58117. }
  58118. }
  58119. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  58120. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  58121. this.world.addEventListener("preStep", impostor.beforeStep);
  58122. this.world.addEventListener("postStep", impostor.afterStep);
  58123. impostor.physicsBody.addShape(shape);
  58124. this.world.add(impostor.physicsBody);
  58125. //try to keep the body moving in the right direction by taking old properties.
  58126. //Should be tested!
  58127. if (oldBody) {
  58128. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  58129. impostor.physicsBody[param].copy(oldBody[param]);
  58130. });
  58131. }
  58132. this._processChildMeshes(impostor);
  58133. }
  58134. //now update the body's transformation
  58135. this._updatePhysicsBodyTransformation(impostor);
  58136. };
  58137. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  58138. var _this = this;
  58139. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  58140. if (meshChildren.length) {
  58141. var processMesh = function (localPosition, mesh) {
  58142. var childImpostor = mesh.getPhysicsImpostor();
  58143. if (childImpostor) {
  58144. var parent = childImpostor.parent;
  58145. if (parent !== mainImpostor) {
  58146. var localPosition = mesh.position;
  58147. if (childImpostor.physicsBody) {
  58148. _this.removePhysicsBody(childImpostor);
  58149. childImpostor.physicsBody = null;
  58150. }
  58151. childImpostor.parent = mainImpostor;
  58152. childImpostor.resetUpdateFlags();
  58153. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  58154. //Add the mass of the children.
  58155. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  58156. }
  58157. }
  58158. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  58159. };
  58160. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  58161. }
  58162. };
  58163. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  58164. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  58165. this.world.removeEventListener("preStep", impostor.beforeStep);
  58166. this.world.removeEventListener("postStep", impostor.afterStep);
  58167. this.world.remove(impostor.physicsBody);
  58168. };
  58169. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  58170. var mainBody = impostorJoint.mainImpostor.physicsBody;
  58171. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  58172. if (!mainBody || !connectedBody) {
  58173. return;
  58174. }
  58175. var constraint;
  58176. var jointData = impostorJoint.joint.jointData;
  58177. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  58178. var constraintData = {
  58179. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  58180. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  58181. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  58182. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  58183. maxForce: jointData.nativeParams.maxForce,
  58184. collideConnected: !!jointData.collision
  58185. };
  58186. switch (impostorJoint.joint.type) {
  58187. case BABYLON.PhysicsJoint.HingeJoint:
  58188. case BABYLON.PhysicsJoint.Hinge2Joint:
  58189. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  58190. break;
  58191. case BABYLON.PhysicsJoint.DistanceJoint:
  58192. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  58193. break;
  58194. case BABYLON.PhysicsJoint.SpringJoint:
  58195. var springData = jointData;
  58196. constraint = new CANNON.Spring(mainBody, connectedBody, {
  58197. restLength: springData.length,
  58198. stiffness: springData.stiffness,
  58199. damping: springData.damping,
  58200. localAnchorA: constraintData.pivotA,
  58201. localAnchorB: constraintData.pivotB
  58202. });
  58203. break;
  58204. case BABYLON.PhysicsJoint.LockJoint:
  58205. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  58206. break;
  58207. case BABYLON.PhysicsJoint.PointToPointJoint:
  58208. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  58209. default:
  58210. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  58211. break;
  58212. }
  58213. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  58214. constraint.collideConnected = !!jointData.collision;
  58215. impostorJoint.joint.physicsJoint = constraint;
  58216. //don't add spring as constraint, as it is not one.
  58217. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  58218. this.world.addConstraint(constraint);
  58219. }
  58220. else {
  58221. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  58222. constraint.applyForce();
  58223. });
  58224. }
  58225. };
  58226. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  58227. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  58228. };
  58229. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  58230. var index;
  58231. var mat;
  58232. for (index = 0; index < this._physicsMaterials.length; index++) {
  58233. mat = this._physicsMaterials[index];
  58234. if (mat.friction === friction && mat.restitution === restitution) {
  58235. return mat;
  58236. }
  58237. }
  58238. var currentMat = new CANNON.Material(name);
  58239. currentMat.friction = friction;
  58240. currentMat.restitution = restitution;
  58241. this._physicsMaterials.push(currentMat);
  58242. return currentMat;
  58243. };
  58244. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  58245. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  58246. };
  58247. CannonJSPlugin.prototype._createShape = function (impostor) {
  58248. var object = impostor.object;
  58249. var returnValue;
  58250. var extendSize = impostor.getObjectExtendSize();
  58251. switch (impostor.type) {
  58252. case BABYLON.PhysicsImpostor.SphereImpostor:
  58253. var radiusX = extendSize.x;
  58254. var radiusY = extendSize.y;
  58255. var radiusZ = extendSize.z;
  58256. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  58257. break;
  58258. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  58259. case BABYLON.PhysicsImpostor.CylinderImpostor:
  58260. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  58261. break;
  58262. case BABYLON.PhysicsImpostor.BoxImpostor:
  58263. var box = extendSize.scale(0.5);
  58264. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  58265. break;
  58266. case BABYLON.PhysicsImpostor.PlaneImpostor:
  58267. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  58268. returnValue = new CANNON.Plane();
  58269. break;
  58270. case BABYLON.PhysicsImpostor.MeshImpostor:
  58271. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  58272. var rawFaces = object.getIndices ? object.getIndices() : [];
  58273. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  58274. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  58275. break;
  58276. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  58277. returnValue = this._createHeightmap(object);
  58278. break;
  58279. case BABYLON.PhysicsImpostor.ParticleImpostor:
  58280. returnValue = new CANNON.Particle();
  58281. break;
  58282. }
  58283. return returnValue;
  58284. };
  58285. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  58286. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58287. var matrix = [];
  58288. //For now pointDepth will not be used and will be automatically calculated.
  58289. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  58290. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  58291. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  58292. var elementSize = dim * 2 / arraySize;
  58293. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  58294. for (var i = 0; i < pos.length; i = i + 3) {
  58295. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  58296. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  58297. var y = pos[i + 1] + minY;
  58298. if (!matrix[x]) {
  58299. matrix[x] = [];
  58300. }
  58301. if (!matrix[x][z]) {
  58302. matrix[x][z] = y;
  58303. }
  58304. matrix[x][z] = Math.max(y, matrix[x][z]);
  58305. }
  58306. for (var x = 0; x <= arraySize; ++x) {
  58307. if (!matrix[x]) {
  58308. var loc = 1;
  58309. while (!matrix[(x + loc) % arraySize]) {
  58310. loc++;
  58311. }
  58312. matrix[x] = matrix[(x + loc) % arraySize].slice();
  58313. //console.log("missing x", x);
  58314. }
  58315. for (var z = 0; z <= arraySize; ++z) {
  58316. if (!matrix[x][z]) {
  58317. var loc = 1;
  58318. var newValue;
  58319. while (newValue === undefined) {
  58320. newValue = matrix[x][(z + loc++) % arraySize];
  58321. }
  58322. matrix[x][z] = newValue;
  58323. }
  58324. }
  58325. }
  58326. var shape = new CANNON.Heightfield(matrix, {
  58327. elementSize: elementSize
  58328. });
  58329. //For future reference, needed for body transformation
  58330. shape.minY = minY;
  58331. return shape;
  58332. };
  58333. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  58334. var object = impostor.object;
  58335. //make sure it is updated...
  58336. object.computeWorldMatrix && object.computeWorldMatrix(true);
  58337. // The delta between the mesh position and the mesh bounding box center
  58338. var center = impostor.getObjectCenter();
  58339. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  58340. this._tmpPosition.copyFrom(center);
  58341. var quaternion = object.rotationQuaternion;
  58342. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  58343. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  58344. //-90 DEG in X, precalculated
  58345. quaternion = quaternion.multiply(this._minus90X);
  58346. //Invert! (Precalculated, 90 deg in X)
  58347. //No need to clone. this will never change.
  58348. impostor.setDeltaRotation(this._plus90X);
  58349. }
  58350. //If it is a heightfield, if should be centered.
  58351. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  58352. var mesh = object;
  58353. //calculate the correct body position:
  58354. var rotationQuaternion = mesh.rotationQuaternion;
  58355. mesh.rotationQuaternion = this._tmpUnityRotation;
  58356. mesh.computeWorldMatrix(true);
  58357. //get original center with no rotation
  58358. var c = center.clone();
  58359. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  58360. //rotation is back
  58361. mesh.rotationQuaternion = rotationQuaternion;
  58362. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  58363. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  58364. mesh.setPivotMatrix(p);
  58365. mesh.computeWorldMatrix(true);
  58366. //calculate the translation
  58367. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  58368. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  58369. //add it inverted to the delta
  58370. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  58371. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  58372. mesh.setPivotMatrix(oldPivot);
  58373. mesh.computeWorldMatrix(true);
  58374. }
  58375. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  58376. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  58377. this._tmpPosition.copyFrom(object.position);
  58378. }
  58379. impostor.setDeltaPosition(this._tmpDeltaPosition);
  58380. //Now update the impostor object
  58381. impostor.physicsBody.position.copy(this._tmpPosition);
  58382. impostor.physicsBody.quaternion.copy(quaternion);
  58383. };
  58384. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  58385. impostor.object.position.copyFrom(impostor.physicsBody.position);
  58386. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  58387. };
  58388. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  58389. impostor.physicsBody.position.copy(newPosition);
  58390. impostor.physicsBody.quaternion.copy(newRotation);
  58391. };
  58392. CannonJSPlugin.prototype.isSupported = function () {
  58393. return window.CANNON !== undefined;
  58394. };
  58395. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  58396. impostor.physicsBody.velocity.copy(velocity);
  58397. };
  58398. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  58399. impostor.physicsBody.angularVelocity.copy(velocity);
  58400. };
  58401. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  58402. var v = impostor.physicsBody.velocity;
  58403. if (!v)
  58404. return null;
  58405. return new BABYLON.Vector3(v.x, v.y, v.z);
  58406. };
  58407. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  58408. var v = impostor.physicsBody.angularVelocity;
  58409. if (!v)
  58410. return null;
  58411. return new BABYLON.Vector3(v.x, v.y, v.z);
  58412. };
  58413. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  58414. impostor.physicsBody.mass = mass;
  58415. impostor.physicsBody.updateMassProperties();
  58416. };
  58417. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  58418. impostor.physicsBody.sleep();
  58419. };
  58420. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  58421. impostor.physicsBody.wakeUp();
  58422. };
  58423. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  58424. joint.physicsJoint.distance = maxDistance;
  58425. };
  58426. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  58427. if (!motorIndex) {
  58428. joint.physicsJoint.enableMotor();
  58429. }
  58430. };
  58431. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  58432. if (!motorIndex) {
  58433. joint.physicsJoint.disableMotor();
  58434. }
  58435. };
  58436. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  58437. if (!motorIndex) {
  58438. joint.physicsJoint.enableMotor();
  58439. joint.physicsJoint.setMotorSpeed(speed);
  58440. if (maxForce) {
  58441. this.setLimit(joint, maxForce);
  58442. }
  58443. }
  58444. };
  58445. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  58446. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  58447. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  58448. };
  58449. CannonJSPlugin.prototype.dispose = function () {
  58450. //nothing to do, actually.
  58451. };
  58452. return CannonJSPlugin;
  58453. }());
  58454. BABYLON.CannonJSPlugin = CannonJSPlugin;
  58455. })(BABYLON || (BABYLON = {}));
  58456. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  58457. var BABYLON;
  58458. (function (BABYLON) {
  58459. var OimoJSPlugin = (function () {
  58460. function OimoJSPlugin(iterations) {
  58461. this.name = "OimoJSPlugin";
  58462. this._tmpImpostorsArray = [];
  58463. this._tmpPositionVector = BABYLON.Vector3.Zero();
  58464. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  58465. this.world.worldscale(1);
  58466. this.world.clear();
  58467. //making sure no stats are calculated
  58468. this.world.isNoStat = true;
  58469. }
  58470. OimoJSPlugin.prototype.setGravity = function (gravity) {
  58471. this.world.gravity.copy(gravity);
  58472. };
  58473. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  58474. this.world.timeStep = timeStep;
  58475. };
  58476. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  58477. var _this = this;
  58478. impostors.forEach(function (impostor) {
  58479. impostor.beforeStep();
  58480. });
  58481. this.world.step();
  58482. impostors.forEach(function (impostor) {
  58483. impostor.afterStep();
  58484. //update the ordered impostors array
  58485. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  58486. });
  58487. //check for collisions
  58488. var contact = this.world.contacts;
  58489. while (contact !== null) {
  58490. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  58491. contact = contact.next;
  58492. continue;
  58493. }
  58494. //is this body colliding with any other? get the impostor
  58495. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  58496. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  58497. if (!mainImpostor || !collidingImpostor) {
  58498. contact = contact.next;
  58499. continue;
  58500. }
  58501. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  58502. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  58503. contact = contact.next;
  58504. }
  58505. };
  58506. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  58507. var mass = impostor.physicsBody.massInfo.mass;
  58508. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  58509. };
  58510. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  58511. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  58512. this.applyImpulse(impostor, force, contactPoint);
  58513. };
  58514. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  58515. var _this = this;
  58516. //parent-child relationship. Does this impostor has a parent impostor?
  58517. if (impostor.parent) {
  58518. if (impostor.physicsBody) {
  58519. this.removePhysicsBody(impostor);
  58520. //TODO is that needed?
  58521. impostor.forceUpdate();
  58522. }
  58523. return;
  58524. }
  58525. if (impostor.isBodyInitRequired()) {
  58526. var bodyConfig = {
  58527. name: impostor.uniqueId,
  58528. //Oimo must have mass, also for static objects.
  58529. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  58530. size: [],
  58531. type: [],
  58532. pos: [],
  58533. rot: [],
  58534. move: impostor.getParam("mass") !== 0,
  58535. //Supporting older versions of Oimo
  58536. world: this.world
  58537. };
  58538. var impostors = [impostor];
  58539. var addToArray = function (parent) {
  58540. if (!parent.getChildMeshes)
  58541. return;
  58542. parent.getChildMeshes().forEach(function (m) {
  58543. if (m.physicsImpostor) {
  58544. impostors.push(m.physicsImpostor);
  58545. m.physicsImpostor._init();
  58546. }
  58547. });
  58548. };
  58549. addToArray(impostor.object);
  58550. var checkWithEpsilon_1 = function (value) {
  58551. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  58552. };
  58553. impostors.forEach(function (i) {
  58554. //get the correct bounding box
  58555. var oldQuaternion = i.object.rotationQuaternion;
  58556. var rot = new OIMO.Euler().setFromQuaternion({
  58557. x: impostor.object.rotationQuaternion.x,
  58558. y: impostor.object.rotationQuaternion.y,
  58559. z: impostor.object.rotationQuaternion.z,
  58560. s: impostor.object.rotationQuaternion.w
  58561. });
  58562. var extendSize = i.getObjectExtendSize();
  58563. if (i === impostor) {
  58564. var center = impostor.getObjectCenter();
  58565. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  58566. //Can also use Array.prototype.push.apply
  58567. bodyConfig.pos.push(center.x);
  58568. bodyConfig.pos.push(center.y);
  58569. bodyConfig.pos.push(center.z);
  58570. //tmp solution
  58571. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  58572. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  58573. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  58574. }
  58575. else {
  58576. bodyConfig.pos.push(i.object.position.x);
  58577. bodyConfig.pos.push(i.object.position.y);
  58578. bodyConfig.pos.push(i.object.position.z);
  58579. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  58580. bodyConfig.rot.push(0);
  58581. bodyConfig.rot.push(0);
  58582. bodyConfig.rot.push(0);
  58583. }
  58584. // register mesh
  58585. switch (i.type) {
  58586. case BABYLON.PhysicsImpostor.ParticleImpostor:
  58587. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  58588. case BABYLON.PhysicsImpostor.SphereImpostor:
  58589. var radiusX = extendSize.x;
  58590. var radiusY = extendSize.y;
  58591. var radiusZ = extendSize.z;
  58592. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  58593. bodyConfig.type.push('sphere');
  58594. //due to the way oimo works with compounds, add 3 times
  58595. bodyConfig.size.push(size);
  58596. bodyConfig.size.push(size);
  58597. bodyConfig.size.push(size);
  58598. break;
  58599. case BABYLON.PhysicsImpostor.CylinderImpostor:
  58600. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  58601. var sizeY = checkWithEpsilon_1(extendSize.y);
  58602. bodyConfig.type.push('cylinder');
  58603. bodyConfig.size.push(sizeX);
  58604. bodyConfig.size.push(sizeY);
  58605. //due to the way oimo works with compounds, add one more value.
  58606. bodyConfig.size.push(sizeY);
  58607. break;
  58608. case BABYLON.PhysicsImpostor.PlaneImpostor:
  58609. case BABYLON.PhysicsImpostor.BoxImpostor:
  58610. default:
  58611. var sizeX = checkWithEpsilon_1(extendSize.x);
  58612. var sizeY = checkWithEpsilon_1(extendSize.y);
  58613. var sizeZ = checkWithEpsilon_1(extendSize.z);
  58614. bodyConfig.type.push('box');
  58615. bodyConfig.size.push(sizeX);
  58616. bodyConfig.size.push(sizeY);
  58617. bodyConfig.size.push(sizeZ);
  58618. break;
  58619. }
  58620. //actually not needed, but hey...
  58621. i.object.rotationQuaternion = oldQuaternion;
  58622. });
  58623. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  58624. }
  58625. else {
  58626. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  58627. }
  58628. impostor.setDeltaPosition(this._tmpPositionVector);
  58629. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  58630. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  58631. };
  58632. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  58633. //impostor.physicsBody.dispose();
  58634. //Same as : (older oimo versions)
  58635. this.world.removeRigidBody(impostor.physicsBody);
  58636. };
  58637. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  58638. var mainBody = impostorJoint.mainImpostor.physicsBody;
  58639. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  58640. if (!mainBody || !connectedBody) {
  58641. return;
  58642. }
  58643. var jointData = impostorJoint.joint.jointData;
  58644. var options = jointData.nativeParams || {};
  58645. var type;
  58646. var nativeJointData = {
  58647. body1: mainBody,
  58648. body2: connectedBody,
  58649. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  58650. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  58651. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  58652. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  58653. min: options.min,
  58654. max: options.max,
  58655. collision: options.collision || jointData.collision,
  58656. spring: options.spring,
  58657. //supporting older version of Oimo
  58658. world: this.world
  58659. };
  58660. switch (impostorJoint.joint.type) {
  58661. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  58662. type = "jointBall";
  58663. break;
  58664. case BABYLON.PhysicsJoint.SpringJoint:
  58665. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  58666. var springData = jointData;
  58667. nativeJointData.min = springData.length || nativeJointData.min;
  58668. //Max should also be set, just make sure it is at least min
  58669. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  58670. case BABYLON.PhysicsJoint.DistanceJoint:
  58671. type = "jointDistance";
  58672. nativeJointData.max = jointData.maxDistance;
  58673. break;
  58674. case BABYLON.PhysicsJoint.PrismaticJoint:
  58675. type = "jointPrisme";
  58676. break;
  58677. case BABYLON.PhysicsJoint.SliderJoint:
  58678. type = "jointSlide";
  58679. break;
  58680. case BABYLON.PhysicsJoint.WheelJoint:
  58681. type = "jointWheel";
  58682. break;
  58683. case BABYLON.PhysicsJoint.HingeJoint:
  58684. default:
  58685. type = "jointHinge";
  58686. break;
  58687. }
  58688. nativeJointData.type = type;
  58689. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  58690. };
  58691. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  58692. //Bug in Oimo prevents us from disposing a joint in the playground
  58693. //joint.joint.physicsJoint.dispose();
  58694. //So we will bruteforce it!
  58695. try {
  58696. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  58697. }
  58698. catch (e) {
  58699. BABYLON.Tools.Warn(e);
  58700. }
  58701. };
  58702. OimoJSPlugin.prototype.isSupported = function () {
  58703. return OIMO !== undefined;
  58704. };
  58705. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  58706. if (!impostor.physicsBody.sleeping) {
  58707. //TODO check that
  58708. if (impostor.physicsBody.shapes.next) {
  58709. var parentShape = this._getLastShape(impostor.physicsBody);
  58710. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  58711. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  58712. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  58713. }
  58714. else {
  58715. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  58716. }
  58717. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  58718. impostor.object.rotationQuaternion.normalize();
  58719. }
  58720. };
  58721. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  58722. var body = impostor.physicsBody;
  58723. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  58724. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  58725. body.syncShapes();
  58726. body.awake();
  58727. };
  58728. OimoJSPlugin.prototype._getLastShape = function (body) {
  58729. var lastShape = body.shapes;
  58730. while (lastShape.next) {
  58731. lastShape = lastShape.next;
  58732. }
  58733. return lastShape;
  58734. };
  58735. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  58736. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  58737. };
  58738. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  58739. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  58740. };
  58741. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  58742. var v = impostor.physicsBody.linearVelocity;
  58743. if (!v)
  58744. return null;
  58745. return new BABYLON.Vector3(v.x, v.y, v.z);
  58746. };
  58747. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  58748. var v = impostor.physicsBody.angularVelocity;
  58749. if (!v)
  58750. return null;
  58751. return new BABYLON.Vector3(v.x, v.y, v.z);
  58752. };
  58753. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  58754. var staticBody = mass === 0;
  58755. //this will actually set the body's density and not its mass.
  58756. //But this is how oimo treats the mass variable.
  58757. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  58758. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  58759. };
  58760. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  58761. impostor.physicsBody.sleep();
  58762. };
  58763. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  58764. impostor.physicsBody.awake();
  58765. };
  58766. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  58767. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  58768. if (minDistance !== void 0) {
  58769. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  58770. }
  58771. };
  58772. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  58773. //TODO separate rotational and transational motors.
  58774. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  58775. if (motor) {
  58776. motor.setMotor(speed, maxForce);
  58777. }
  58778. };
  58779. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  58780. //TODO separate rotational and transational motors.
  58781. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  58782. if (motor) {
  58783. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  58784. }
  58785. };
  58786. OimoJSPlugin.prototype.dispose = function () {
  58787. this.world.clear();
  58788. };
  58789. return OimoJSPlugin;
  58790. }());
  58791. BABYLON.OimoJSPlugin = OimoJSPlugin;
  58792. })(BABYLON || (BABYLON = {}));
  58793. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  58794. var BABYLON;
  58795. (function (BABYLON) {
  58796. var Internals;
  58797. (function (Internals) {
  58798. /*
  58799. * Based on jsTGALoader - Javascript loader for TGA file
  58800. * By Vincent Thibault
  58801. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  58802. */
  58803. var TGATools = (function () {
  58804. function TGATools() {
  58805. }
  58806. TGATools.GetTGAHeader = function (data) {
  58807. var offset = 0;
  58808. var header = {
  58809. id_length: data[offset++],
  58810. colormap_type: data[offset++],
  58811. image_type: data[offset++],
  58812. colormap_index: data[offset++] | data[offset++] << 8,
  58813. colormap_length: data[offset++] | data[offset++] << 8,
  58814. colormap_size: data[offset++],
  58815. origin: [
  58816. data[offset++] | data[offset++] << 8,
  58817. data[offset++] | data[offset++] << 8
  58818. ],
  58819. width: data[offset++] | data[offset++] << 8,
  58820. height: data[offset++] | data[offset++] << 8,
  58821. pixel_size: data[offset++],
  58822. flags: data[offset++]
  58823. };
  58824. return header;
  58825. };
  58826. TGATools.UploadContent = function (gl, data) {
  58827. // Not enough data to contain header ?
  58828. if (data.length < 19) {
  58829. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  58830. return;
  58831. }
  58832. // Read Header
  58833. var offset = 18;
  58834. var header = TGATools.GetTGAHeader(data);
  58835. // Assume it's a valid Targa file.
  58836. if (header.id_length + offset > data.length) {
  58837. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  58838. return;
  58839. }
  58840. // Skip not needed data
  58841. offset += header.id_length;
  58842. var use_rle = false;
  58843. var use_pal = false;
  58844. var use_rgb = false;
  58845. var use_grey = false;
  58846. // Get some informations.
  58847. switch (header.image_type) {
  58848. case TGATools._TYPE_RLE_INDEXED:
  58849. use_rle = true;
  58850. case TGATools._TYPE_INDEXED:
  58851. use_pal = true;
  58852. break;
  58853. case TGATools._TYPE_RLE_RGB:
  58854. use_rle = true;
  58855. case TGATools._TYPE_RGB:
  58856. use_rgb = true;
  58857. break;
  58858. case TGATools._TYPE_RLE_GREY:
  58859. use_rle = true;
  58860. case TGATools._TYPE_GREY:
  58861. use_grey = true;
  58862. break;
  58863. }
  58864. var pixel_data;
  58865. var numAlphaBits = header.flags & 0xf;
  58866. var pixel_size = header.pixel_size >> 3;
  58867. var pixel_total = header.width * header.height * pixel_size;
  58868. // Read palettes
  58869. var palettes;
  58870. if (use_pal) {
  58871. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  58872. }
  58873. // Read LRE
  58874. if (use_rle) {
  58875. pixel_data = new Uint8Array(pixel_total);
  58876. var c, count, i;
  58877. var localOffset = 0;
  58878. var pixels = new Uint8Array(pixel_size);
  58879. while (offset < pixel_total && localOffset < pixel_total) {
  58880. c = data[offset++];
  58881. count = (c & 0x7f) + 1;
  58882. // RLE pixels
  58883. if (c & 0x80) {
  58884. // Bind pixel tmp array
  58885. for (i = 0; i < pixel_size; ++i) {
  58886. pixels[i] = data[offset++];
  58887. }
  58888. // Copy pixel array
  58889. for (i = 0; i < count; ++i) {
  58890. pixel_data.set(pixels, localOffset + i * pixel_size);
  58891. }
  58892. localOffset += pixel_size * count;
  58893. }
  58894. else {
  58895. count *= pixel_size;
  58896. for (i = 0; i < count; ++i) {
  58897. pixel_data[localOffset + i] = data[offset++];
  58898. }
  58899. localOffset += count;
  58900. }
  58901. }
  58902. }
  58903. else {
  58904. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  58905. }
  58906. // Load to texture
  58907. var x_start, y_start, x_step, y_step, y_end, x_end;
  58908. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  58909. default:
  58910. case TGATools._ORIGIN_UL:
  58911. x_start = 0;
  58912. x_step = 1;
  58913. x_end = header.width;
  58914. y_start = 0;
  58915. y_step = 1;
  58916. y_end = header.height;
  58917. break;
  58918. case TGATools._ORIGIN_BL:
  58919. x_start = 0;
  58920. x_step = 1;
  58921. x_end = header.width;
  58922. y_start = header.height - 1;
  58923. y_step = -1;
  58924. y_end = -1;
  58925. break;
  58926. case TGATools._ORIGIN_UR:
  58927. x_start = header.width - 1;
  58928. x_step = -1;
  58929. x_end = -1;
  58930. y_start = 0;
  58931. y_step = 1;
  58932. y_end = header.height;
  58933. break;
  58934. case TGATools._ORIGIN_BR:
  58935. x_start = header.width - 1;
  58936. x_step = -1;
  58937. x_end = -1;
  58938. y_start = header.height - 1;
  58939. y_step = -1;
  58940. y_end = -1;
  58941. break;
  58942. }
  58943. // Load the specify method
  58944. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  58945. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  58946. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  58947. };
  58948. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58949. var image = pixel_data, colormap = palettes;
  58950. var width = header.width, height = header.height;
  58951. var color, i = 0, x, y;
  58952. var imageData = new Uint8Array(width * height * 4);
  58953. for (y = y_start; y !== y_end; y += y_step) {
  58954. for (x = x_start; x !== x_end; x += x_step, i++) {
  58955. color = image[i];
  58956. imageData[(x + width * y) * 4 + 3] = 255;
  58957. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  58958. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  58959. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  58960. }
  58961. }
  58962. return imageData;
  58963. };
  58964. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58965. var image = pixel_data;
  58966. var width = header.width, height = header.height;
  58967. var color, i = 0, x, y;
  58968. var imageData = new Uint8Array(width * height * 4);
  58969. for (y = y_start; y !== y_end; y += y_step) {
  58970. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  58971. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  58972. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  58973. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  58974. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  58975. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  58976. }
  58977. }
  58978. return imageData;
  58979. };
  58980. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58981. var image = pixel_data;
  58982. var width = header.width, height = header.height;
  58983. var i = 0, x, y;
  58984. var imageData = new Uint8Array(width * height * 4);
  58985. for (y = y_start; y !== y_end; y += y_step) {
  58986. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  58987. imageData[(x + width * y) * 4 + 3] = 255;
  58988. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  58989. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  58990. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  58991. }
  58992. }
  58993. return imageData;
  58994. };
  58995. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  58996. var image = pixel_data;
  58997. var width = header.width, height = header.height;
  58998. var i = 0, x, y;
  58999. var imageData = new Uint8Array(width * height * 4);
  59000. for (y = y_start; y !== y_end; y += y_step) {
  59001. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  59002. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  59003. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  59004. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  59005. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  59006. }
  59007. }
  59008. return imageData;
  59009. };
  59010. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  59011. var image = pixel_data;
  59012. var width = header.width, height = header.height;
  59013. var color, i = 0, x, y;
  59014. var imageData = new Uint8Array(width * height * 4);
  59015. for (y = y_start; y !== y_end; y += y_step) {
  59016. for (x = x_start; x !== x_end; x += x_step, i++) {
  59017. color = image[i];
  59018. imageData[(x + width * y) * 4 + 0] = color;
  59019. imageData[(x + width * y) * 4 + 1] = color;
  59020. imageData[(x + width * y) * 4 + 2] = color;
  59021. imageData[(x + width * y) * 4 + 3] = 255;
  59022. }
  59023. }
  59024. return imageData;
  59025. };
  59026. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  59027. var image = pixel_data;
  59028. var width = header.width, height = header.height;
  59029. var i = 0, x, y;
  59030. var imageData = new Uint8Array(width * height * 4);
  59031. for (y = y_start; y !== y_end; y += y_step) {
  59032. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  59033. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  59034. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  59035. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  59036. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  59037. }
  59038. }
  59039. return imageData;
  59040. };
  59041. return TGATools;
  59042. }());
  59043. TGATools._TYPE_NO_DATA = 0;
  59044. TGATools._TYPE_INDEXED = 1;
  59045. TGATools._TYPE_RGB = 2;
  59046. TGATools._TYPE_GREY = 3;
  59047. TGATools._TYPE_RLE_INDEXED = 9;
  59048. TGATools._TYPE_RLE_RGB = 10;
  59049. TGATools._TYPE_RLE_GREY = 11;
  59050. TGATools._ORIGIN_MASK = 0x30;
  59051. TGATools._ORIGIN_SHIFT = 0x04;
  59052. TGATools._ORIGIN_BL = 0x00;
  59053. TGATools._ORIGIN_BR = 0x01;
  59054. TGATools._ORIGIN_UL = 0x02;
  59055. TGATools._ORIGIN_UR = 0x03;
  59056. Internals.TGATools = TGATools;
  59057. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59058. })(BABYLON || (BABYLON = {}));
  59059. //# sourceMappingURL=babylon.tga.js.map
  59060. var BABYLON;
  59061. (function (BABYLON) {
  59062. var Internals;
  59063. (function (Internals) {
  59064. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  59065. // All values and structures referenced from:
  59066. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  59067. var DDS_MAGIC = 0x20534444;
  59068. 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;
  59069. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  59070. 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;
  59071. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  59072. function FourCCToInt32(value) {
  59073. return value.charCodeAt(0) +
  59074. (value.charCodeAt(1) << 8) +
  59075. (value.charCodeAt(2) << 16) +
  59076. (value.charCodeAt(3) << 24);
  59077. }
  59078. function Int32ToFourCC(value) {
  59079. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  59080. }
  59081. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  59082. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  59083. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  59084. var headerLengthInt = 31; // The header length in 32 bit ints
  59085. // Offsets into the header array
  59086. var off_magic = 0;
  59087. var off_size = 1;
  59088. var off_flags = 2;
  59089. var off_height = 3;
  59090. var off_width = 4;
  59091. var off_mipmapCount = 7;
  59092. var off_pfFlags = 20;
  59093. var off_pfFourCC = 21;
  59094. var off_RGBbpp = 22;
  59095. var off_RMask = 23;
  59096. var off_GMask = 24;
  59097. var off_BMask = 25;
  59098. var off_AMask = 26;
  59099. var off_caps1 = 27;
  59100. var off_caps2 = 28;
  59101. ;
  59102. var DDSTools = (function () {
  59103. function DDSTools() {
  59104. }
  59105. DDSTools.GetDDSInfo = function (arrayBuffer) {
  59106. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  59107. var mipmapCount = 1;
  59108. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  59109. mipmapCount = Math.max(1, header[off_mipmapCount]);
  59110. }
  59111. return {
  59112. width: header[off_width],
  59113. height: header[off_height],
  59114. mipmapCount: mipmapCount,
  59115. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  59116. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  59117. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  59118. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  59119. };
  59120. };
  59121. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  59122. var byteArray = new Uint8Array(dataLength);
  59123. var srcData = new Uint8Array(arrayBuffer);
  59124. var index = 0;
  59125. for (var y = height - 1; y >= 0; y--) {
  59126. for (var x = 0; x < width; x++) {
  59127. var srcPos = dataOffset + (x + y * width) * 4;
  59128. byteArray[index + 2] = srcData[srcPos];
  59129. byteArray[index + 1] = srcData[srcPos + 1];
  59130. byteArray[index] = srcData[srcPos + 2];
  59131. byteArray[index + 3] = srcData[srcPos + 3];
  59132. index += 4;
  59133. }
  59134. }
  59135. return byteArray;
  59136. };
  59137. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  59138. var byteArray = new Uint8Array(dataLength);
  59139. var srcData = new Uint8Array(arrayBuffer);
  59140. var index = 0;
  59141. for (var y = height - 1; y >= 0; y--) {
  59142. for (var x = 0; x < width; x++) {
  59143. var srcPos = dataOffset + (x + y * width) * 3;
  59144. byteArray[index + 2] = srcData[srcPos];
  59145. byteArray[index + 1] = srcData[srcPos + 1];
  59146. byteArray[index] = srcData[srcPos + 2];
  59147. index += 3;
  59148. }
  59149. }
  59150. return byteArray;
  59151. };
  59152. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  59153. var byteArray = new Uint8Array(dataLength);
  59154. var srcData = new Uint8Array(arrayBuffer);
  59155. var index = 0;
  59156. for (var y = height - 1; y >= 0; y--) {
  59157. for (var x = 0; x < width; x++) {
  59158. var srcPos = dataOffset + (x + y * width);
  59159. byteArray[index] = srcData[srcPos];
  59160. index++;
  59161. }
  59162. }
  59163. return byteArray;
  59164. };
  59165. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  59166. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  59167. if (header[off_magic] != DDS_MAGIC) {
  59168. BABYLON.Tools.Error("Invalid magic number in DDS header");
  59169. return;
  59170. }
  59171. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  59172. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  59173. return;
  59174. }
  59175. if (info.isFourCC) {
  59176. fourCC = header[off_pfFourCC];
  59177. switch (fourCC) {
  59178. case FOURCC_DXT1:
  59179. blockBytes = 8;
  59180. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  59181. break;
  59182. case FOURCC_DXT3:
  59183. blockBytes = 16;
  59184. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  59185. break;
  59186. case FOURCC_DXT5:
  59187. blockBytes = 16;
  59188. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  59189. break;
  59190. default:
  59191. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  59192. return;
  59193. }
  59194. }
  59195. mipmapCount = 1;
  59196. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  59197. mipmapCount = Math.max(1, header[off_mipmapCount]);
  59198. }
  59199. var bpp = header[off_RGBbpp];
  59200. for (var face = 0; face < faces; face++) {
  59201. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  59202. width = header[off_width];
  59203. height = header[off_height];
  59204. dataOffset = header[off_size] + 4;
  59205. for (i = 0; i < mipmapCount; ++i) {
  59206. if (info.isRGB) {
  59207. if (bpp === 24) {
  59208. dataLength = width * height * 3;
  59209. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  59210. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  59211. }
  59212. else {
  59213. dataLength = width * height * 4;
  59214. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  59215. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  59216. }
  59217. }
  59218. else if (info.isLuminance) {
  59219. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  59220. var unpaddedRowSize = width;
  59221. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  59222. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  59223. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  59224. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  59225. }
  59226. else {
  59227. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  59228. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  59229. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  59230. }
  59231. dataOffset += dataLength;
  59232. width *= 0.5;
  59233. height *= 0.5;
  59234. width = Math.max(1.0, width);
  59235. height = Math.max(1.0, height);
  59236. }
  59237. }
  59238. };
  59239. return DDSTools;
  59240. }());
  59241. Internals.DDSTools = DDSTools;
  59242. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59243. })(BABYLON || (BABYLON = {}));
  59244. //# sourceMappingURL=babylon.dds.js.map
  59245. var BABYLON;
  59246. (function (BABYLON) {
  59247. var Internals;
  59248. (function (Internals) {
  59249. /**
  59250. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  59251. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  59252. */
  59253. var KhronosTextureContainer = (function () {
  59254. /**
  59255. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  59256. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  59257. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  59258. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  59259. */
  59260. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  59261. this.arrayBuffer = arrayBuffer;
  59262. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  59263. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  59264. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  59265. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  59266. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  59267. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  59268. BABYLON.Tools.Error("texture missing KTX identifier");
  59269. return;
  59270. }
  59271. // load the reset of the header in native 32 bit int
  59272. var header = new Int32Array(this.arrayBuffer, 12, 13);
  59273. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  59274. var oppositeEndianess = header[0] === 0x01020304;
  59275. // read all the header elements in order they exist in the file, without modification (sans endainness)
  59276. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  59277. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  59278. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  59279. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  59280. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  59281. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  59282. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  59283. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  59284. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  59285. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  59286. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  59287. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  59288. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  59289. if (this.glType !== 0) {
  59290. BABYLON.Tools.Error("only compressed formats currently supported");
  59291. return;
  59292. }
  59293. else {
  59294. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  59295. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  59296. }
  59297. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  59298. BABYLON.Tools.Error("only 2D textures currently supported");
  59299. return;
  59300. }
  59301. if (this.numberOfArrayElements !== 0) {
  59302. BABYLON.Tools.Error("texture arrays not currently supported");
  59303. return;
  59304. }
  59305. if (this.numberOfFaces !== facesExpected) {
  59306. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  59307. return;
  59308. }
  59309. // we now have a completely validated file, so could use existence of loadType as success
  59310. // would need to make this more elaborate & adjust checks above to support more than one load type
  59311. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  59312. }
  59313. // not as fast hardware based, but will probably never need to use
  59314. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  59315. return ((val & 0xFF) << 24)
  59316. | ((val & 0xFF00) << 8)
  59317. | ((val >> 8) & 0xFF00)
  59318. | ((val >> 24) & 0xFF);
  59319. };
  59320. /**
  59321. * It is assumed that the texture has already been created & is currently bound
  59322. */
  59323. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  59324. switch (this.loadType) {
  59325. case KhronosTextureContainer.COMPRESSED_2D:
  59326. this._upload2DCompressedLevels(gl, loadMipmaps);
  59327. break;
  59328. case KhronosTextureContainer.TEX_2D:
  59329. case KhronosTextureContainer.COMPRESSED_3D:
  59330. case KhronosTextureContainer.TEX_3D:
  59331. }
  59332. };
  59333. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  59334. // initialize width & height for level 1
  59335. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  59336. var width = this.pixelWidth;
  59337. var height = this.pixelHeight;
  59338. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  59339. for (var level = 0; level < mipmapCount; level++) {
  59340. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  59341. for (var face = 0; face < this.numberOfFaces; face++) {
  59342. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  59343. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  59344. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  59345. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  59346. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  59347. }
  59348. width = Math.max(1.0, width * 0.5);
  59349. height = Math.max(1.0, height * 0.5);
  59350. }
  59351. };
  59352. return KhronosTextureContainer;
  59353. }());
  59354. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  59355. // load types
  59356. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  59357. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  59358. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  59359. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  59360. Internals.KhronosTextureContainer = KhronosTextureContainer;
  59361. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59362. })(BABYLON || (BABYLON = {}));
  59363. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  59364. var BABYLON;
  59365. (function (BABYLON) {
  59366. var DynamicFloatArrayElementInfo = (function () {
  59367. function DynamicFloatArrayElementInfo() {
  59368. }
  59369. return DynamicFloatArrayElementInfo;
  59370. }());
  59371. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  59372. /**
  59373. * 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.
  59374. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  59375. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  59376. * 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.
  59377. * 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.
  59378. * 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".
  59379. */
  59380. var DynamicFloatArray = (function () {
  59381. /**
  59382. * Construct an instance of the dynamic float array
  59383. * @param stride size of one element in float (i.e. not bytes!)
  59384. * @param initialElementCount the number of available entries at construction
  59385. */
  59386. function DynamicFloatArray(stride, initialElementCount) {
  59387. this.compareValueOffset = null;
  59388. this.sortingAscending = true;
  59389. this._stride = stride;
  59390. this.buffer = new Float32Array(stride * initialElementCount);
  59391. this._lastUsed = 0;
  59392. this._firstFree = 0;
  59393. this._allEntries = new Array(initialElementCount);
  59394. this._freeEntries = new Array(initialElementCount);
  59395. for (var i = 0; i < initialElementCount; i++) {
  59396. var element = new DynamicFloatArrayElementInfo();
  59397. element.offset = i * stride;
  59398. this._allEntries[i] = element;
  59399. this._freeEntries[initialElementCount - i - 1] = element;
  59400. }
  59401. }
  59402. /**
  59403. * Allocate an element in the array.
  59404. * @return the element info instance that contains the offset into the main buffer of the element's location.
  59405. * Beware, this offset may change when you call pack()
  59406. */
  59407. DynamicFloatArray.prototype.allocElement = function () {
  59408. if (this._freeEntries.length === 0) {
  59409. this._growBuffer();
  59410. }
  59411. var el = this._freeEntries.pop();
  59412. this._lastUsed = Math.max(el.offset, this._lastUsed);
  59413. if (el.offset === this._firstFree) {
  59414. if (this._freeEntries.length > 0) {
  59415. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  59416. }
  59417. else {
  59418. this._firstFree += this._stride;
  59419. }
  59420. }
  59421. return el;
  59422. };
  59423. /**
  59424. * Free the element corresponding to the given element info
  59425. * @param elInfo the element that describe the allocated element
  59426. */
  59427. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  59428. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  59429. this._freeEntries.push(elInfo);
  59430. };
  59431. /**
  59432. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  59433. * 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().
  59434. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  59435. */
  59436. DynamicFloatArray.prototype.pack = function () {
  59437. // no free slot? no need to pack
  59438. if (this._freeEntries.length === 0) {
  59439. return this.buffer;
  59440. }
  59441. // If the buffer is already packed the last used will always be lower than the first free
  59442. // 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.
  59443. if (this._lastUsed < this._firstFree) {
  59444. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  59445. return elementsBuffer_1;
  59446. }
  59447. var s = this._stride;
  59448. // 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
  59449. var lastFree = new DynamicFloatArrayElementInfo();
  59450. lastFree.offset = this.totalElementCount * s;
  59451. this._freeEntries.push(lastFree);
  59452. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  59453. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  59454. var firstFreeSlotOffset = sortedFree[0].offset;
  59455. var freeZoneSize = 1;
  59456. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  59457. var prevOffset = sortedFree[0].offset;
  59458. for (var i = 1; i < sortedFree.length; i++) {
  59459. // 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
  59460. if (firstFreeSlotOffset >= occupiedZoneSize) {
  59461. break;
  59462. }
  59463. var curFree = sortedFree[i];
  59464. var curOffset = curFree.offset;
  59465. // Compute the distance between this offset and the previous
  59466. var distance = curOffset - prevOffset;
  59467. // If the distance is the stride size, they are adjacent, it good, move to the next
  59468. if (distance === s) {
  59469. // Free zone is one element bigger
  59470. ++freeZoneSize;
  59471. // as we're about to iterate to the next, the cur becomes the previous...
  59472. prevOffset = curOffset;
  59473. continue;
  59474. }
  59475. // Distance is bigger, which means there's x element between the previous free and this one
  59476. var usedRange = (distance / s) - 1;
  59477. // Two cases the free zone is smaller than the data to move or bigger
  59478. // Copy what can fit in the free zone
  59479. var curMoveOffset = curOffset - s;
  59480. var copyCount = Math.min(freeZoneSize, usedRange);
  59481. for (var j = 0; j < copyCount; j++) {
  59482. var freeI = firstFreeSlotOffset / s;
  59483. var curI = curMoveOffset / s;
  59484. var moveEl = sortedAll[curI];
  59485. this._moveElement(moveEl, firstFreeSlotOffset);
  59486. var replacedEl = sortedAll[freeI];
  59487. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  59488. replacedEl.offset = curMoveOffset;
  59489. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  59490. sortedAll[freeI] = moveEl;
  59491. sortedAll[curI] = replacedEl;
  59492. curMoveOffset -= s;
  59493. firstFreeSlotOffset += s;
  59494. }
  59495. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  59496. if (freeZoneSize <= usedRange) {
  59497. firstFreeSlotOffset = curMoveOffset + s;
  59498. freeZoneSize = 1 + copyCount;
  59499. }
  59500. else {
  59501. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  59502. }
  59503. // as we're about to iterate to the next, the cur becomes the previous...
  59504. prevOffset = curOffset;
  59505. }
  59506. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  59507. this._lastUsed = firstFreeSlotOffset - s;
  59508. this._firstFree = firstFreeSlotOffset;
  59509. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  59510. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  59511. this._allEntries = sortedAll;
  59512. return elementsBuffer;
  59513. };
  59514. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  59515. for (var i = 0; i < this._stride; i++) {
  59516. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  59517. }
  59518. element.offset = destOffset;
  59519. };
  59520. DynamicFloatArray.prototype._growBuffer = function () {
  59521. // Allocate the new buffer with 50% more entries, copy the content of the current one
  59522. var newElCount = Math.floor(this.totalElementCount * 1.5);
  59523. var newBuffer = new Float32Array(newElCount * this._stride);
  59524. newBuffer.set(this.buffer);
  59525. var curCount = this.totalElementCount;
  59526. var addedCount = newElCount - this.totalElementCount;
  59527. for (var i = 0; i < addedCount; i++) {
  59528. var element = new DynamicFloatArrayElementInfo();
  59529. element.offset = (curCount + i) * this.stride;
  59530. this._allEntries.push(element);
  59531. this._freeEntries[addedCount - i - 1] = element;
  59532. }
  59533. this._firstFree = curCount * this.stride;
  59534. this.buffer = newBuffer;
  59535. };
  59536. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  59537. /**
  59538. * Get the total count of entries that can fit in the current buffer
  59539. * @returns the elements count
  59540. */
  59541. get: function () {
  59542. return this._allEntries.length;
  59543. },
  59544. enumerable: true,
  59545. configurable: true
  59546. });
  59547. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  59548. /**
  59549. * Get the count of free entries that can still be allocated without resizing the buffer
  59550. * @returns the free elements count
  59551. */
  59552. get: function () {
  59553. return this._freeEntries.length;
  59554. },
  59555. enumerable: true,
  59556. configurable: true
  59557. });
  59558. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  59559. /**
  59560. * Get the count of allocated elements
  59561. * @returns the allocated elements count
  59562. */
  59563. get: function () {
  59564. return this._allEntries.length - this._freeEntries.length;
  59565. },
  59566. enumerable: true,
  59567. configurable: true
  59568. });
  59569. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  59570. /**
  59571. * Return the size of one element in float
  59572. * @returns the size in float
  59573. */
  59574. get: function () {
  59575. return this._stride;
  59576. },
  59577. enumerable: true,
  59578. configurable: true
  59579. });
  59580. DynamicFloatArray.prototype.sort = function () {
  59581. var _this = this;
  59582. if (!this.compareValueOffset) {
  59583. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  59584. }
  59585. var count = this.usedElementCount;
  59586. // Do we have to (re)create the sort table?
  59587. if (!this._sortTable || this._sortTable.length < count) {
  59588. // 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...
  59589. var newCount = Math.min(this.totalElementCount, count * 2);
  59590. this._sortTable = new Array(newCount);
  59591. }
  59592. if (!this._sortedTable || this._sortedTable.length !== count) {
  59593. this._sortedTable = new Array(count);
  59594. }
  59595. // Because, you know...
  59596. this.pack();
  59597. //let stride = this.stride;
  59598. //for (let i = 0; i < count; i++) {
  59599. // let si = this._sortTable[i];
  59600. // if (!si) {
  59601. // si = new SortInfo();
  59602. // this._sortTable[i] = si;
  59603. // }
  59604. // si.entry = this._allEntries[i];
  59605. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  59606. // si.swapedOffset = null;
  59607. // this._sortedTable[i] = si;
  59608. //}
  59609. var curOffset = 0;
  59610. var stride = this.stride;
  59611. for (var i = 0; i < count; i++, curOffset += stride) {
  59612. var si = this._sortTable[i];
  59613. if (!si) {
  59614. si = new SortInfo();
  59615. this._sortTable[i] = si;
  59616. }
  59617. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  59618. si.offset = curOffset;
  59619. si.swapedOffset = null;
  59620. this._sortedTable[i] = si;
  59621. }
  59622. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  59623. if (this.sortingAscending) {
  59624. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  59625. }
  59626. else {
  59627. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  59628. }
  59629. var swapElements = function (src, dst) {
  59630. for (var i = 0; i < stride; i++) {
  59631. var tps = _this.buffer[dst + i];
  59632. _this.buffer[dst + i] = _this.buffer[src + i];
  59633. _this.buffer[src + i] = tps;
  59634. }
  59635. };
  59636. // 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:
  59637. // 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),
  59638. // and I still want something with a good algorithm complexity.
  59639. // 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,
  59640. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  59641. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  59642. // 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
  59643. // until we find a SortInfo object without a swapedOffset which means we got the right location
  59644. // 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
  59645. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  59646. for (var i = 0; i < count; i++) {
  59647. // Get the element to move
  59648. var sourceSI = this._sortedTable[i];
  59649. var destSI = this._sortTable[i];
  59650. var sourceOff = sourceSI.offset;
  59651. // If the source changed location, find the new one
  59652. if (sourceSI.swapedOffset) {
  59653. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  59654. var curSI = sourceSI;
  59655. while (curSI.swapedOffset) {
  59656. curSI = this._sortTable[curSI.swapedOffset / stride];
  59657. }
  59658. // Finally get the right location
  59659. sourceOff = curSI.offset;
  59660. }
  59661. // Tag the element being replaced with its new location
  59662. destSI.swapedOffset = sourceOff;
  59663. // Swap elements (only if needed)
  59664. if (sourceOff !== destSI.offset) {
  59665. swapElements(sourceOff, destSI.offset);
  59666. }
  59667. // Update the offset in the corresponding DFAE
  59668. //sourceSI.entry.offset = destSI.entry.offset;
  59669. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  59670. }
  59671. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  59672. return true;
  59673. };
  59674. return DynamicFloatArray;
  59675. }());
  59676. BABYLON.DynamicFloatArray = DynamicFloatArray;
  59677. var SortInfo = (function () {
  59678. function SortInfo() {
  59679. this.compareData = this.offset = this.swapedOffset = null;
  59680. }
  59681. return SortInfo;
  59682. }());
  59683. })(BABYLON || (BABYLON = {}));
  59684. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  59685. var BABYLON;
  59686. (function (BABYLON) {
  59687. var Debug;
  59688. (function (Debug) {
  59689. /**
  59690. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59691. */
  59692. var SkeletonViewer = (function () {
  59693. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59694. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59695. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59696. this.skeleton = skeleton;
  59697. this.mesh = mesh;
  59698. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59699. this.renderingGroupId = renderingGroupId;
  59700. this.color = BABYLON.Color3.White();
  59701. this._debugLines = [];
  59702. this._isEnabled = false;
  59703. this._scene = scene;
  59704. this.update();
  59705. this._renderFunction = this.update.bind(this);
  59706. }
  59707. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59708. get: function () {
  59709. return this._isEnabled;
  59710. },
  59711. set: function (value) {
  59712. if (this._isEnabled === value) {
  59713. return;
  59714. }
  59715. this._isEnabled = value;
  59716. if (value) {
  59717. this._scene.registerBeforeRender(this._renderFunction);
  59718. }
  59719. else {
  59720. this._scene.unregisterBeforeRender(this._renderFunction);
  59721. }
  59722. },
  59723. enumerable: true,
  59724. configurable: true
  59725. });
  59726. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59727. if (x === void 0) { x = 0; }
  59728. if (y === void 0) { y = 0; }
  59729. if (z === void 0) { z = 0; }
  59730. var tmat = BABYLON.Tmp.Matrix[0];
  59731. var parentBone = bone.getParent();
  59732. tmat.copyFrom(bone.getLocalMatrix());
  59733. if (x !== 0 || y !== 0 || z !== 0) {
  59734. var tmat2 = BABYLON.Tmp.Matrix[1];
  59735. BABYLON.Matrix.IdentityToRef(tmat2);
  59736. tmat2.m[12] = x;
  59737. tmat2.m[13] = y;
  59738. tmat2.m[14] = z;
  59739. tmat2.multiplyToRef(tmat, tmat);
  59740. }
  59741. if (parentBone) {
  59742. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59743. }
  59744. tmat.multiplyToRef(meshMat, tmat);
  59745. position.x = tmat.m[12];
  59746. position.y = tmat.m[13];
  59747. position.z = tmat.m[14];
  59748. };
  59749. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59750. var len = bones.length;
  59751. var meshPos = this.mesh.position;
  59752. for (var i = 0; i < len; i++) {
  59753. var bone = bones[i];
  59754. var points = this._debugLines[i];
  59755. if (!points) {
  59756. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59757. this._debugLines[i] = points;
  59758. }
  59759. this._getBonePosition(points[0], bone, meshMat);
  59760. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59761. points[0].subtractInPlace(meshPos);
  59762. points[1].subtractInPlace(meshPos);
  59763. }
  59764. };
  59765. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59766. var len = bones.length;
  59767. var boneNum = 0;
  59768. var meshPos = this.mesh.position;
  59769. for (var i = len - 1; i >= 0; i--) {
  59770. var childBone = bones[i];
  59771. var parentBone = childBone.getParent();
  59772. if (!parentBone) {
  59773. continue;
  59774. }
  59775. var points = this._debugLines[boneNum];
  59776. if (!points) {
  59777. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59778. this._debugLines[boneNum] = points;
  59779. }
  59780. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59781. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59782. points[0].subtractInPlace(meshPos);
  59783. points[1].subtractInPlace(meshPos);
  59784. boneNum++;
  59785. }
  59786. };
  59787. SkeletonViewer.prototype.update = function () {
  59788. if (this.autoUpdateBonesMatrices) {
  59789. this.skeleton.computeAbsoluteTransforms();
  59790. }
  59791. if (this.skeleton.bones[0].length === undefined) {
  59792. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59793. }
  59794. else {
  59795. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59796. }
  59797. if (!this._debugMesh) {
  59798. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59799. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59800. }
  59801. else {
  59802. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59803. }
  59804. this._debugMesh.position.copyFrom(this.mesh.position);
  59805. this._debugMesh.color = this.color;
  59806. };
  59807. SkeletonViewer.prototype.dispose = function () {
  59808. if (this._debugMesh) {
  59809. this.isEnabled = false;
  59810. this._debugMesh.dispose();
  59811. this._debugMesh = null;
  59812. }
  59813. };
  59814. return SkeletonViewer;
  59815. }());
  59816. Debug.SkeletonViewer = SkeletonViewer;
  59817. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59818. })(BABYLON || (BABYLON = {}));
  59819. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59820. var BABYLON;
  59821. (function (BABYLON) {
  59822. var Debug;
  59823. (function (Debug) {
  59824. var AxesViewer = (function () {
  59825. function AxesViewer(scene, scaleLines) {
  59826. if (scaleLines === void 0) { scaleLines = 1; }
  59827. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59828. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59829. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59830. this.scaleLines = 1;
  59831. this.scaleLines = scaleLines;
  59832. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59833. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59834. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59835. this._xmesh.renderingGroupId = 2;
  59836. this._ymesh.renderingGroupId = 2;
  59837. this._zmesh.renderingGroupId = 2;
  59838. this._xmesh.material.checkReadyOnlyOnce = true;
  59839. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59840. this._ymesh.material.checkReadyOnlyOnce = true;
  59841. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59842. this._zmesh.material.checkReadyOnlyOnce = true;
  59843. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59844. this.scene = scene;
  59845. }
  59846. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59847. var scaleLines = this.scaleLines;
  59848. this._xmesh.position.copyFrom(position);
  59849. this._ymesh.position.copyFrom(position);
  59850. this._zmesh.position.copyFrom(position);
  59851. var point2 = this._xline[1];
  59852. point2.x = xaxis.x * scaleLines;
  59853. point2.y = xaxis.y * scaleLines;
  59854. point2.z = xaxis.z * scaleLines;
  59855. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  59856. point2 = this._yline[1];
  59857. point2.x = yaxis.x * scaleLines;
  59858. point2.y = yaxis.y * scaleLines;
  59859. point2.z = yaxis.z * scaleLines;
  59860. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  59861. point2 = this._zline[1];
  59862. point2.x = zaxis.x * scaleLines;
  59863. point2.y = zaxis.y * scaleLines;
  59864. point2.z = zaxis.z * scaleLines;
  59865. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  59866. };
  59867. AxesViewer.prototype.dispose = function () {
  59868. if (this._xmesh) {
  59869. this._xmesh.dispose();
  59870. this._ymesh.dispose();
  59871. this._zmesh.dispose();
  59872. this._xmesh = null;
  59873. this._ymesh = null;
  59874. this._zmesh = null;
  59875. this._xline = null;
  59876. this._yline = null;
  59877. this._zline = null;
  59878. this.scene = null;
  59879. }
  59880. };
  59881. return AxesViewer;
  59882. }());
  59883. Debug.AxesViewer = AxesViewer;
  59884. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59885. })(BABYLON || (BABYLON = {}));
  59886. //# sourceMappingURL=babylon.axesViewer.js.map
  59887. var BABYLON;
  59888. (function (BABYLON) {
  59889. var Debug;
  59890. (function (Debug) {
  59891. var BoneAxesViewer = (function (_super) {
  59892. __extends(BoneAxesViewer, _super);
  59893. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59894. if (scaleLines === void 0) { scaleLines = 1; }
  59895. var _this = _super.call(this, scene, scaleLines) || this;
  59896. _this.pos = BABYLON.Vector3.Zero();
  59897. _this.xaxis = BABYLON.Vector3.Zero();
  59898. _this.yaxis = BABYLON.Vector3.Zero();
  59899. _this.zaxis = BABYLON.Vector3.Zero();
  59900. _this.mesh = mesh;
  59901. _this.bone = bone;
  59902. return _this;
  59903. }
  59904. BoneAxesViewer.prototype.update = function () {
  59905. var bone = this.bone;
  59906. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59907. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59908. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59909. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59910. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59911. };
  59912. BoneAxesViewer.prototype.dispose = function () {
  59913. if (this.pos) {
  59914. this.pos = null;
  59915. this.xaxis = null;
  59916. this.yaxis = null;
  59917. this.zaxis = null;
  59918. this.mesh = null;
  59919. this.bone = null;
  59920. _super.prototype.dispose.call(this);
  59921. }
  59922. };
  59923. return BoneAxesViewer;
  59924. }(Debug.AxesViewer));
  59925. Debug.BoneAxesViewer = BoneAxesViewer;
  59926. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59927. })(BABYLON || (BABYLON = {}));
  59928. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59929. var BABYLON;
  59930. (function (BABYLON) {
  59931. var RayHelper = (function () {
  59932. function RayHelper(ray) {
  59933. this.ray = ray;
  59934. }
  59935. RayHelper.CreateAndShow = function (ray, scene, color) {
  59936. var helper = new RayHelper(ray);
  59937. helper.show(scene, color);
  59938. return helper;
  59939. };
  59940. RayHelper.prototype.show = function (scene, color) {
  59941. if (!this._renderFunction) {
  59942. var ray = this.ray;
  59943. this._renderFunction = this._render.bind(this);
  59944. this._scene = scene;
  59945. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  59946. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  59947. this._scene.registerBeforeRender(this._renderFunction);
  59948. }
  59949. if (color) {
  59950. this._renderLine.color.copyFrom(color);
  59951. }
  59952. };
  59953. RayHelper.prototype.hide = function () {
  59954. if (this._renderFunction) {
  59955. this._scene.unregisterBeforeRender(this._renderFunction);
  59956. this._scene = null;
  59957. this._renderFunction = null;
  59958. this._renderLine.dispose();
  59959. this._renderLine = null;
  59960. this._renderPoints = null;
  59961. }
  59962. };
  59963. RayHelper.prototype._render = function () {
  59964. var ray = this.ray;
  59965. var point = this._renderPoints[1];
  59966. var len = Math.min(ray.length, 1000000);
  59967. point.copyFrom(ray.direction);
  59968. point.scaleInPlace(len);
  59969. point.addInPlace(ray.origin);
  59970. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  59971. };
  59972. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  59973. this._attachedToMesh = mesh;
  59974. var ray = this.ray;
  59975. if (!ray.direction) {
  59976. ray.direction = BABYLON.Vector3.Zero();
  59977. }
  59978. if (!ray.origin) {
  59979. ray.origin = BABYLON.Vector3.Zero();
  59980. }
  59981. if (length) {
  59982. ray.length = length;
  59983. }
  59984. if (!meshSpaceOrigin) {
  59985. meshSpaceOrigin = BABYLON.Vector3.Zero();
  59986. }
  59987. if (!meshSpaceDirection) {
  59988. // -1 so that this will work with Mesh.lookAt
  59989. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  59990. }
  59991. if (!this._meshSpaceDirection) {
  59992. this._meshSpaceDirection = meshSpaceDirection.clone();
  59993. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  59994. }
  59995. else {
  59996. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  59997. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  59998. }
  59999. if (!this._updateToMeshFunction) {
  60000. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60001. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60002. }
  60003. this._updateToMesh();
  60004. };
  60005. RayHelper.prototype.detachFromMesh = function () {
  60006. if (this._attachedToMesh) {
  60007. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60008. this._attachedToMesh = null;
  60009. this._updateToMeshFunction = null;
  60010. }
  60011. };
  60012. RayHelper.prototype._updateToMesh = function () {
  60013. var ray = this.ray;
  60014. if (this._attachedToMesh._isDisposed) {
  60015. this.detachFromMesh();
  60016. return;
  60017. }
  60018. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60019. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60020. };
  60021. RayHelper.prototype.dispose = function () {
  60022. this.hide();
  60023. this.detachFromMesh();
  60024. this.ray = null;
  60025. };
  60026. return RayHelper;
  60027. }());
  60028. BABYLON.RayHelper = RayHelper;
  60029. })(BABYLON || (BABYLON = {}));
  60030. //# sourceMappingURL=babylon.rayHelper.js.map
  60031. var BABYLON;
  60032. (function (BABYLON) {
  60033. var DebugLayer = (function () {
  60034. function DebugLayer(scene) {
  60035. this._scene = scene;
  60036. }
  60037. /** Creates the inspector window. */
  60038. DebugLayer.prototype._createInspector = function (config) {
  60039. if (config === void 0) { config = {}; }
  60040. var popup = config.popup || false;
  60041. var initialTab = config.initialTab || 0;
  60042. var parentElement = config.parentElement || null;
  60043. if (!this._inspector) {
  60044. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60045. } // else nothing to do,; instance is already existing
  60046. };
  60047. DebugLayer.prototype.isVisible = function () {
  60048. if (!this._inspector) {
  60049. return false;
  60050. }
  60051. return true;
  60052. };
  60053. DebugLayer.prototype.hide = function () {
  60054. if (this._inspector) {
  60055. try {
  60056. this._inspector.dispose();
  60057. }
  60058. catch (e) {
  60059. // If the inspector has been removed directly from the inspector tool
  60060. }
  60061. this._inspector = null;
  60062. }
  60063. };
  60064. DebugLayer.prototype.show = function (config) {
  60065. if (config === void 0) { config = {}; }
  60066. if (typeof INSPECTOR == 'undefined') {
  60067. // Load inspector and add it to the DOM
  60068. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60069. }
  60070. else {
  60071. // Otherwise creates the inspector
  60072. this._createInspector(config);
  60073. }
  60074. };
  60075. return DebugLayer;
  60076. }());
  60077. // Get protocol used - http or https
  60078. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  60079. BABYLON.DebugLayer = DebugLayer;
  60080. })(BABYLON || (BABYLON = {}));
  60081. //# sourceMappingURL=babylon.debugLayer.js.map
  60082. var BABYLON;
  60083. (function (BABYLON) {
  60084. var BoundingBoxRenderer = (function () {
  60085. function BoundingBoxRenderer(scene) {
  60086. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60087. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60088. this.showBackLines = true;
  60089. this.renderList = new BABYLON.SmartArray(32);
  60090. this._vertexBuffers = {};
  60091. this._scene = scene;
  60092. }
  60093. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60094. if (this._colorShader) {
  60095. return;
  60096. }
  60097. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  60098. attributes: [BABYLON.VertexBuffer.PositionKind],
  60099. uniforms: ["world", "viewProjection", "color"]
  60100. });
  60101. var engine = this._scene.getEngine();
  60102. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  60103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60104. 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]);
  60105. };
  60106. BoundingBoxRenderer.prototype.reset = function () {
  60107. this.renderList.reset();
  60108. };
  60109. BoundingBoxRenderer.prototype.render = function () {
  60110. if (this.renderList.length === 0) {
  60111. return;
  60112. }
  60113. this._prepareRessources();
  60114. if (!this._colorShader.isReady()) {
  60115. return;
  60116. }
  60117. var engine = this._scene.getEngine();
  60118. engine.setDepthWrite(false);
  60119. this._colorShader._preBind();
  60120. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60121. var boundingBox = this.renderList.data[boundingBoxIndex];
  60122. var min = boundingBox.minimum;
  60123. var max = boundingBox.maximum;
  60124. var diff = max.subtract(min);
  60125. var median = min.add(diff.scale(0.5));
  60126. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60127. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60128. .multiply(boundingBox.getWorldMatrix());
  60129. // VBOs
  60130. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60131. if (this.showBackLines) {
  60132. // Back
  60133. engine.setDepthFunctionToGreaterOrEqual();
  60134. this._scene.resetCachedMaterial();
  60135. this._colorShader.setColor4("color", this.backColor.toColor4());
  60136. this._colorShader.bind(worldMatrix);
  60137. // Draw order
  60138. engine.draw(false, 0, 24);
  60139. }
  60140. // Front
  60141. engine.setDepthFunctionToLess();
  60142. this._scene.resetCachedMaterial();
  60143. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60144. this._colorShader.bind(worldMatrix);
  60145. // Draw order
  60146. engine.draw(false, 0, 24);
  60147. }
  60148. this._colorShader.unbind();
  60149. engine.setDepthFunctionToLessOrEqual();
  60150. engine.setDepthWrite(true);
  60151. };
  60152. BoundingBoxRenderer.prototype.dispose = function () {
  60153. if (!this._colorShader) {
  60154. return;
  60155. }
  60156. this.renderList.dispose();
  60157. this._colorShader.dispose();
  60158. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60159. if (buffer) {
  60160. buffer.dispose();
  60161. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60162. }
  60163. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60164. };
  60165. return BoundingBoxRenderer;
  60166. }());
  60167. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60168. })(BABYLON || (BABYLON = {}));
  60169. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60170. var BABYLON;
  60171. (function (BABYLON) {
  60172. var MorphTarget = (function () {
  60173. function MorphTarget(name, influence) {
  60174. if (influence === void 0) { influence = 0; }
  60175. this.name = name;
  60176. this.animations = new Array();
  60177. this.onInfluenceChanged = new BABYLON.Observable();
  60178. this.influence = influence;
  60179. }
  60180. Object.defineProperty(MorphTarget.prototype, "influence", {
  60181. get: function () {
  60182. return this._influence;
  60183. },
  60184. set: function (influence) {
  60185. if (this._influence === influence) {
  60186. return;
  60187. }
  60188. var previous = this._influence;
  60189. this._influence = influence;
  60190. if (this.onInfluenceChanged.hasObservers) {
  60191. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  60192. }
  60193. },
  60194. enumerable: true,
  60195. configurable: true
  60196. });
  60197. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  60198. get: function () {
  60199. return this._normals !== undefined;
  60200. },
  60201. enumerable: true,
  60202. configurable: true
  60203. });
  60204. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  60205. get: function () {
  60206. return this._tangents !== undefined;
  60207. },
  60208. enumerable: true,
  60209. configurable: true
  60210. });
  60211. MorphTarget.prototype.setPositions = function (data) {
  60212. this._positions = new Float32Array(data);
  60213. };
  60214. MorphTarget.prototype.getPositions = function () {
  60215. return this._positions;
  60216. };
  60217. MorphTarget.prototype.setNormals = function (data) {
  60218. this._normals = new Float32Array(data);
  60219. };
  60220. MorphTarget.prototype.getNormals = function () {
  60221. return this._normals;
  60222. };
  60223. MorphTarget.prototype.setTangents = function (data) {
  60224. this._tangents = new Float32Array(data);
  60225. };
  60226. MorphTarget.prototype.getTangents = function () {
  60227. return this._tangents;
  60228. };
  60229. /**
  60230. * Serializes the current target into a Serialization object.
  60231. * Returns the serialized object.
  60232. */
  60233. MorphTarget.prototype.serialize = function () {
  60234. var serializationObject = {};
  60235. serializationObject.name = this.name;
  60236. serializationObject.influence = this.influence;
  60237. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  60238. if (this.hasNormals) {
  60239. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  60240. }
  60241. if (this.hasTangents) {
  60242. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  60243. }
  60244. return serializationObject;
  60245. };
  60246. // Statics
  60247. MorphTarget.Parse = function (serializationObject) {
  60248. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  60249. result.setPositions(serializationObject.positions);
  60250. if (serializationObject.normals) {
  60251. result.setNormals(serializationObject.normals);
  60252. }
  60253. if (serializationObject.tangents) {
  60254. result.setTangents(serializationObject.tangents);
  60255. }
  60256. return result;
  60257. };
  60258. MorphTarget.FromMesh = function (mesh, name, influence) {
  60259. if (!name) {
  60260. name = mesh.name;
  60261. }
  60262. var result = new MorphTarget(name, influence);
  60263. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  60264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60265. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  60266. }
  60267. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  60268. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  60269. }
  60270. return result;
  60271. };
  60272. return MorphTarget;
  60273. }());
  60274. BABYLON.MorphTarget = MorphTarget;
  60275. })(BABYLON || (BABYLON = {}));
  60276. //# sourceMappingURL=babylon.morphTarget.js.map
  60277. var BABYLON;
  60278. (function (BABYLON) {
  60279. var MorphTargetManager = (function () {
  60280. function MorphTargetManager(scene) {
  60281. this._targets = new Array();
  60282. this._targetObservable = new Array();
  60283. this._activeTargets = new BABYLON.SmartArray(16);
  60284. this._supportsNormals = false;
  60285. this._supportsTangents = false;
  60286. this._vertexCount = 0;
  60287. this._uniqueId = 0;
  60288. if (!scene) {
  60289. scene = BABYLON.Engine.LastCreatedScene;
  60290. }
  60291. this._scene = scene;
  60292. this._scene.morphTargetManagers.push(this);
  60293. this._uniqueId = scene.getUniqueId();
  60294. }
  60295. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  60296. get: function () {
  60297. return this._uniqueId;
  60298. },
  60299. enumerable: true,
  60300. configurable: true
  60301. });
  60302. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  60303. get: function () {
  60304. return this._vertexCount;
  60305. },
  60306. enumerable: true,
  60307. configurable: true
  60308. });
  60309. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  60310. get: function () {
  60311. return this._supportsNormals;
  60312. },
  60313. enumerable: true,
  60314. configurable: true
  60315. });
  60316. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  60317. get: function () {
  60318. return this._supportsTangents;
  60319. },
  60320. enumerable: true,
  60321. configurable: true
  60322. });
  60323. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  60324. get: function () {
  60325. return this._targets.length;
  60326. },
  60327. enumerable: true,
  60328. configurable: true
  60329. });
  60330. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  60331. get: function () {
  60332. return this._activeTargets.length;
  60333. },
  60334. enumerable: true,
  60335. configurable: true
  60336. });
  60337. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  60338. get: function () {
  60339. return this._influences;
  60340. },
  60341. enumerable: true,
  60342. configurable: true
  60343. });
  60344. MorphTargetManager.prototype.getActiveTarget = function (index) {
  60345. return this._activeTargets.data[index];
  60346. };
  60347. MorphTargetManager.prototype.getTarget = function (index) {
  60348. return this._targets[index];
  60349. };
  60350. MorphTargetManager.prototype.addTarget = function (target) {
  60351. var _this = this;
  60352. if (this._vertexCount) {
  60353. if (this._vertexCount !== target.getPositions().length / 3) {
  60354. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  60355. return;
  60356. }
  60357. }
  60358. this._targets.push(target);
  60359. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  60360. _this._syncActiveTargets(needUpdate);
  60361. }));
  60362. this._syncActiveTargets(true);
  60363. };
  60364. MorphTargetManager.prototype.removeTarget = function (target) {
  60365. var index = this._targets.indexOf(target);
  60366. if (index >= 0) {
  60367. this._targets.splice(index, 1);
  60368. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  60369. this._vertexCount = 0;
  60370. this._syncActiveTargets(true);
  60371. }
  60372. };
  60373. /**
  60374. * Serializes the current manager into a Serialization object.
  60375. * Returns the serialized object.
  60376. */
  60377. MorphTargetManager.prototype.serialize = function () {
  60378. var serializationObject = {};
  60379. serializationObject.id = this.uniqueId;
  60380. serializationObject.targets = [];
  60381. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  60382. var target = _a[_i];
  60383. serializationObject.targets.push(target.serialize());
  60384. }
  60385. return serializationObject;
  60386. };
  60387. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  60388. this._syncActiveTargets(needUpdate);
  60389. };
  60390. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  60391. this._activeTargets.reset();
  60392. var tempInfluences = [];
  60393. this._supportsNormals = true;
  60394. this._supportsTangents = true;
  60395. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  60396. var target = _a[_i];
  60397. if (target.influence > 0) {
  60398. this._activeTargets.push(target);
  60399. tempInfluences.push(target.influence);
  60400. this._supportsNormals = this._supportsNormals && target.hasNormals;
  60401. this._supportsTangents = this._supportsTangents && target.hasTangents;
  60402. if (this._vertexCount === 0) {
  60403. this._vertexCount = target.getPositions().length / 3;
  60404. }
  60405. }
  60406. }
  60407. this._influences = new Float32Array(tempInfluences);
  60408. if (needUpdate) {
  60409. // Flag meshes as dirty to resync with the active targets
  60410. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  60411. var mesh = _c[_b];
  60412. if (mesh.morphTargetManager === this) {
  60413. mesh._syncGeometryWithMorphTargetManager();
  60414. }
  60415. }
  60416. }
  60417. };
  60418. // Statics
  60419. MorphTargetManager.Parse = function (serializationObject, scene) {
  60420. var result = new MorphTargetManager(scene);
  60421. result._uniqueId = serializationObject.id;
  60422. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  60423. var targetData = _a[_i];
  60424. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  60425. }
  60426. return result;
  60427. };
  60428. return MorphTargetManager;
  60429. }());
  60430. BABYLON.MorphTargetManager = MorphTargetManager;
  60431. })(BABYLON || (BABYLON = {}));
  60432. //# sourceMappingURL=babylon.morphTargetManager.js.map
  60433. var BABYLON;
  60434. (function (BABYLON) {
  60435. /**
  60436. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60437. * It can help converting any input color in a desired output one. This can then be used to create effects
  60438. * from sepia, black and white to sixties or futuristic rendering...
  60439. *
  60440. * The only supported format is currently 3dl.
  60441. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60442. */
  60443. var ColorGradingTexture = (function (_super) {
  60444. __extends(ColorGradingTexture, _super);
  60445. /**
  60446. * Instantiates a ColorGradingTexture from the following parameters.
  60447. *
  60448. * @param url The location of the color gradind data (currently only supporting 3dl)
  60449. * @param scene The scene the texture will be used in
  60450. */
  60451. function ColorGradingTexture(url, scene) {
  60452. var _this = _super.call(this, scene) || this;
  60453. if (!url) {
  60454. return _this;
  60455. }
  60456. _this._textureMatrix = BABYLON.Matrix.Identity();
  60457. _this.name = url;
  60458. _this.url = url;
  60459. _this.hasAlpha = false;
  60460. _this.isCube = false;
  60461. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60462. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60463. _this.anisotropicFilteringLevel = 1;
  60464. _this._texture = _this._getFromCache(url, true);
  60465. if (!_this._texture) {
  60466. if (!scene.useDelayedTextureLoading) {
  60467. _this.loadTexture();
  60468. }
  60469. else {
  60470. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60471. }
  60472. }
  60473. return _this;
  60474. }
  60475. /**
  60476. * Returns the texture matrix used in most of the material.
  60477. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60478. */
  60479. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60480. return this._textureMatrix;
  60481. };
  60482. /**
  60483. * Occurs when the file being loaded is a .3dl LUT file.
  60484. */
  60485. ColorGradingTexture.prototype.load3dlTexture = function () {
  60486. var _this = this;
  60487. var mipLevels = 0;
  60488. var floatArrayView = null;
  60489. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60490. this._texture = texture;
  60491. var callback = function (text) {
  60492. var data;
  60493. var tempData;
  60494. var line;
  60495. var lines = text.split('\n');
  60496. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60497. var maxColor = 0;
  60498. for (var i = 0; i < lines.length; i++) {
  60499. line = lines[i];
  60500. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60501. continue;
  60502. if (line.indexOf('#') === 0)
  60503. continue;
  60504. var words = line.split(" ");
  60505. if (size === 0) {
  60506. // Number of space + one
  60507. size = words.length;
  60508. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60509. tempData = new Float32Array(size * size * size * 4);
  60510. continue;
  60511. }
  60512. if (size != 0) {
  60513. var r = Math.max(parseInt(words[0]), 0);
  60514. var g = Math.max(parseInt(words[1]), 0);
  60515. var b = Math.max(parseInt(words[2]), 0);
  60516. maxColor = Math.max(r, maxColor);
  60517. maxColor = Math.max(g, maxColor);
  60518. maxColor = Math.max(b, maxColor);
  60519. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60520. tempData[pixelStorageIndex + 0] = r;
  60521. tempData[pixelStorageIndex + 1] = g;
  60522. tempData[pixelStorageIndex + 2] = b;
  60523. tempData[pixelStorageIndex + 3] = 0;
  60524. pixelIndexSlice++;
  60525. if (pixelIndexSlice % size == 0) {
  60526. pixelIndexH++;
  60527. pixelIndexSlice = 0;
  60528. if (pixelIndexH % size == 0) {
  60529. pixelIndexW++;
  60530. pixelIndexH = 0;
  60531. }
  60532. }
  60533. }
  60534. }
  60535. for (var i = 0; i < tempData.length; i++) {
  60536. var value = tempData[i];
  60537. data[i] = (value / maxColor * 255);
  60538. }
  60539. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60540. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60541. };
  60542. BABYLON.Tools.LoadFile(this.url, callback);
  60543. return this._texture;
  60544. };
  60545. /**
  60546. * Starts the loading process of the texture.
  60547. */
  60548. ColorGradingTexture.prototype.loadTexture = function () {
  60549. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60550. this.load3dlTexture();
  60551. }
  60552. };
  60553. /**
  60554. * Clones the color gradind texture.
  60555. */
  60556. ColorGradingTexture.prototype.clone = function () {
  60557. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60558. // Base texture
  60559. newTexture.level = this.level;
  60560. return newTexture;
  60561. };
  60562. /**
  60563. * Called during delayed load for textures.
  60564. */
  60565. ColorGradingTexture.prototype.delayLoad = function () {
  60566. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60567. return;
  60568. }
  60569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60570. this._texture = this._getFromCache(this.url, true);
  60571. if (!this._texture) {
  60572. this.loadTexture();
  60573. }
  60574. };
  60575. /**
  60576. * Binds the color grading to the shader.
  60577. * @param colorGrading The texture to bind
  60578. * @param effect The effect to bind to
  60579. */
  60580. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60581. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60582. var x = colorGrading.level; // Texture Level
  60583. var y = colorGrading.getSize().height; // Texture Size example with 8
  60584. var z = y - 1.0; // SizeMinusOne 8 - 1
  60585. var w = 1 / y; // Space of 1 slice 1 / 8
  60586. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60587. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60588. 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
  60589. 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
  60590. 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
  60591. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60592. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60593. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60594. };
  60595. /**
  60596. * Prepare the list of uniforms associated with the ColorGrading effects.
  60597. * @param uniformsList The list of uniforms used in the effect
  60598. * @param samplersList The list of samplers used in the effect
  60599. */
  60600. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60601. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60602. samplersList.push("cameraColorGrading2DSampler");
  60603. };
  60604. /**
  60605. * Parses a color grading texture serialized by Babylon.
  60606. * @param parsedTexture The texture information being parsedTexture
  60607. * @param scene The scene to load the texture in
  60608. * @param rootUrl The root url of the data assets to load
  60609. * @return A color gradind texture
  60610. */
  60611. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60612. var texture = null;
  60613. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60614. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60615. texture.name = parsedTexture.name;
  60616. texture.level = parsedTexture.level;
  60617. }
  60618. return texture;
  60619. };
  60620. /**
  60621. * Serializes the LUT texture to json format.
  60622. */
  60623. ColorGradingTexture.prototype.serialize = function () {
  60624. if (!this.name) {
  60625. return null;
  60626. }
  60627. var serializationObject = {};
  60628. serializationObject.name = this.name;
  60629. serializationObject.level = this.level;
  60630. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60631. return serializationObject;
  60632. };
  60633. return ColorGradingTexture;
  60634. }(BABYLON.BaseTexture));
  60635. /**
  60636. * Empty line regex stored for GC.
  60637. */
  60638. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60639. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60640. })(BABYLON || (BABYLON = {}));
  60641. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  60642. var BABYLON;
  60643. (function (BABYLON) {
  60644. /**
  60645. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60646. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60647. * 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;
  60648. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60649. */
  60650. var ColorCurves = (function () {
  60651. function ColorCurves() {
  60652. this._dirty = true;
  60653. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  60654. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  60655. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60656. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  60657. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  60658. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  60659. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  60660. this._globalHue = 30;
  60661. this._globalDensity = 0;
  60662. this._globalSaturation = 0;
  60663. this._globalExposure = 0;
  60664. this._highlightsHue = 30;
  60665. this._highlightsDensity = 0;
  60666. this._highlightsSaturation = 0;
  60667. this._highlightsExposure = 0;
  60668. this._midtonesHue = 30;
  60669. this._midtonesDensity = 0;
  60670. this._midtonesSaturation = 0;
  60671. this._midtonesExposure = 0;
  60672. this._shadowsHue = 30;
  60673. this._shadowsDensity = 0;
  60674. this._shadowsSaturation = 0;
  60675. this._shadowsExposure = 0;
  60676. }
  60677. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  60678. /**
  60679. * Gets the global Hue value.
  60680. * 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).
  60681. */
  60682. get: function () {
  60683. return this._globalHue;
  60684. },
  60685. /**
  60686. * Sets the global Hue value.
  60687. * 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).
  60688. */
  60689. set: function (value) {
  60690. this._globalHue = value;
  60691. this._dirty = true;
  60692. },
  60693. enumerable: true,
  60694. configurable: true
  60695. });
  60696. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  60697. /**
  60698. * Gets the global Density value.
  60699. * 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.
  60700. * Values less than zero provide a filter of opposite hue.
  60701. */
  60702. get: function () {
  60703. return this._globalDensity;
  60704. },
  60705. /**
  60706. * Sets the global Density value.
  60707. * 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.
  60708. * Values less than zero provide a filter of opposite hue.
  60709. */
  60710. set: function (value) {
  60711. this._globalDensity = value;
  60712. this._dirty = true;
  60713. },
  60714. enumerable: true,
  60715. configurable: true
  60716. });
  60717. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  60718. /**
  60719. * Gets the global Saturation value.
  60720. * 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.
  60721. */
  60722. get: function () {
  60723. return this._globalSaturation;
  60724. },
  60725. /**
  60726. * Sets the global Saturation value.
  60727. * 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.
  60728. */
  60729. set: function (value) {
  60730. this._globalSaturation = value;
  60731. this._dirty = true;
  60732. },
  60733. enumerable: true,
  60734. configurable: true
  60735. });
  60736. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  60737. /**
  60738. * Gets the highlights Hue value.
  60739. * 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).
  60740. */
  60741. get: function () {
  60742. return this._highlightsHue;
  60743. },
  60744. /**
  60745. * Sets the highlights Hue value.
  60746. * 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).
  60747. */
  60748. set: function (value) {
  60749. this._highlightsHue = value;
  60750. this._dirty = true;
  60751. },
  60752. enumerable: true,
  60753. configurable: true
  60754. });
  60755. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  60756. /**
  60757. * Gets the highlights Density value.
  60758. * 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.
  60759. * Values less than zero provide a filter of opposite hue.
  60760. */
  60761. get: function () {
  60762. return this._highlightsDensity;
  60763. },
  60764. /**
  60765. * Sets the highlights Density value.
  60766. * 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.
  60767. * Values less than zero provide a filter of opposite hue.
  60768. */
  60769. set: function (value) {
  60770. this._highlightsDensity = value;
  60771. this._dirty = true;
  60772. },
  60773. enumerable: true,
  60774. configurable: true
  60775. });
  60776. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  60777. /**
  60778. * Gets the highlights Saturation value.
  60779. * 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.
  60780. */
  60781. get: function () {
  60782. return this._highlightsSaturation;
  60783. },
  60784. /**
  60785. * Sets the highlights Saturation value.
  60786. * 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.
  60787. */
  60788. set: function (value) {
  60789. this._highlightsSaturation = value;
  60790. this._dirty = true;
  60791. },
  60792. enumerable: true,
  60793. configurable: true
  60794. });
  60795. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  60796. /**
  60797. * Gets the highlights Exposure value.
  60798. * 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.
  60799. */
  60800. get: function () {
  60801. return this._highlightsExposure;
  60802. },
  60803. /**
  60804. * Sets the highlights Exposure value.
  60805. * 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.
  60806. */
  60807. set: function (value) {
  60808. this._highlightsExposure = value;
  60809. this._dirty = true;
  60810. },
  60811. enumerable: true,
  60812. configurable: true
  60813. });
  60814. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  60815. /**
  60816. * Gets the midtones Hue value.
  60817. * 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).
  60818. */
  60819. get: function () {
  60820. return this._midtonesHue;
  60821. },
  60822. /**
  60823. * Sets the midtones Hue value.
  60824. * 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).
  60825. */
  60826. set: function (value) {
  60827. this._midtonesHue = value;
  60828. this._dirty = true;
  60829. },
  60830. enumerable: true,
  60831. configurable: true
  60832. });
  60833. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  60834. /**
  60835. * Gets the midtones Density value.
  60836. * 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.
  60837. * Values less than zero provide a filter of opposite hue.
  60838. */
  60839. get: function () {
  60840. return this._midtonesDensity;
  60841. },
  60842. /**
  60843. * Sets the midtones Density value.
  60844. * 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.
  60845. * Values less than zero provide a filter of opposite hue.
  60846. */
  60847. set: function (value) {
  60848. this._midtonesDensity = value;
  60849. this._dirty = true;
  60850. },
  60851. enumerable: true,
  60852. configurable: true
  60853. });
  60854. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  60855. /**
  60856. * Gets the midtones Saturation value.
  60857. * 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.
  60858. */
  60859. get: function () {
  60860. return this._midtonesSaturation;
  60861. },
  60862. /**
  60863. * Sets the midtones Saturation value.
  60864. * 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.
  60865. */
  60866. set: function (value) {
  60867. this._midtonesSaturation = value;
  60868. this._dirty = true;
  60869. },
  60870. enumerable: true,
  60871. configurable: true
  60872. });
  60873. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  60874. /**
  60875. * Gets the midtones Exposure value.
  60876. * 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.
  60877. */
  60878. get: function () {
  60879. return this._midtonesExposure;
  60880. },
  60881. /**
  60882. * Sets the midtones Exposure value.
  60883. * 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.
  60884. */
  60885. set: function (value) {
  60886. this._midtonesExposure = value;
  60887. this._dirty = true;
  60888. },
  60889. enumerable: true,
  60890. configurable: true
  60891. });
  60892. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  60893. /**
  60894. * Gets the shadows Hue value.
  60895. * 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).
  60896. */
  60897. get: function () {
  60898. return this._shadowsHue;
  60899. },
  60900. /**
  60901. * Sets the shadows Hue value.
  60902. * 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).
  60903. */
  60904. set: function (value) {
  60905. this._shadowsHue = value;
  60906. this._dirty = true;
  60907. },
  60908. enumerable: true,
  60909. configurable: true
  60910. });
  60911. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  60912. /**
  60913. * Gets the shadows Density value.
  60914. * 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.
  60915. * Values less than zero provide a filter of opposite hue.
  60916. */
  60917. get: function () {
  60918. return this._shadowsDensity;
  60919. },
  60920. /**
  60921. * Sets the shadows Density value.
  60922. * 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.
  60923. * Values less than zero provide a filter of opposite hue.
  60924. */
  60925. set: function (value) {
  60926. this._shadowsDensity = value;
  60927. this._dirty = true;
  60928. },
  60929. enumerable: true,
  60930. configurable: true
  60931. });
  60932. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  60933. /**
  60934. * Gets the shadows Saturation value.
  60935. * 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.
  60936. */
  60937. get: function () {
  60938. return this._shadowsSaturation;
  60939. },
  60940. /**
  60941. * Sets the shadows Saturation value.
  60942. * 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.
  60943. */
  60944. set: function (value) {
  60945. this._shadowsSaturation = value;
  60946. this._dirty = true;
  60947. },
  60948. enumerable: true,
  60949. configurable: true
  60950. });
  60951. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  60952. /**
  60953. * Gets the shadows Exposure value.
  60954. * 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.
  60955. */
  60956. get: function () {
  60957. return this._shadowsExposure;
  60958. },
  60959. /**
  60960. * Sets the shadows Exposure value.
  60961. * 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.
  60962. */
  60963. set: function (value) {
  60964. this._shadowsExposure = value;
  60965. this._dirty = true;
  60966. },
  60967. enumerable: true,
  60968. configurable: true
  60969. });
  60970. /**
  60971. * Binds the color curves to the shader.
  60972. * @param colorCurves The color curve to bind
  60973. * @param effect The effect to bind to
  60974. */
  60975. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  60976. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  60977. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  60978. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  60979. if (colorCurves._dirty) {
  60980. colorCurves._dirty = false;
  60981. // Fill in global info.
  60982. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60983. // Compute highlights info.
  60984. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60985. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60986. // Compute midtones info.
  60987. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60988. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60989. // Compute shadows info.
  60990. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60991. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60992. // Compute deltas (neutral is midtones).
  60993. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60994. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60995. }
  60996. if (effect) {
  60997. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60998. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60999. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  61000. }
  61001. };
  61002. /**
  61003. * Prepare the list of uniforms associated with the ColorCurves effects.
  61004. * @param uniformsList The list of uniforms used in the effect
  61005. */
  61006. ColorCurves.PrepareUniforms = function (uniformsList) {
  61007. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  61008. };
  61009. /**
  61010. * Returns color grading data based on a hue, density, saturation and exposure value.
  61011. * @param filterHue The hue of the color filter.
  61012. * @param filterDensity The density of the color filter.
  61013. * @param saturation The saturation.
  61014. * @param exposure The exposure.
  61015. * @param result The result data container.
  61016. */
  61017. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  61018. if (hue == null) {
  61019. return;
  61020. }
  61021. hue = ColorCurves.clamp(hue, 0, 360);
  61022. density = ColorCurves.clamp(density, -100, 100);
  61023. saturation = ColorCurves.clamp(saturation, -100, 100);
  61024. exposure = ColorCurves.clamp(exposure, -100, 100);
  61025. // Remap the slider/config filter density with non-linear mapping and also scale by half
  61026. // so that the maximum filter density is only 50% control. This provides fine control
  61027. // for small values and reasonable range.
  61028. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  61029. density *= 0.5;
  61030. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  61031. if (density < 0) {
  61032. density *= -1;
  61033. hue = (hue + 180) % 360;
  61034. }
  61035. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  61036. result.scaleToRef(2, result);
  61037. result.a = 1 + 0.01 * saturation;
  61038. };
  61039. /**
  61040. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  61041. * @param value The input slider value in range [-100,100].
  61042. * @returns Adjusted value.
  61043. */
  61044. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  61045. value /= 100;
  61046. var x = Math.abs(value);
  61047. x = Math.pow(x, 2);
  61048. if (value < 0) {
  61049. x *= -1;
  61050. }
  61051. x *= 100;
  61052. return x;
  61053. };
  61054. /**
  61055. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  61056. * @param hue The hue (H) input.
  61057. * @param saturation The saturation (S) input.
  61058. * @param brightness The brightness (B) input.
  61059. * @result An RGBA color represented as Vector4.
  61060. */
  61061. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  61062. var h = ColorCurves.clamp(hue, 0, 360);
  61063. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  61064. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  61065. if (s === 0) {
  61066. result.r = v;
  61067. result.g = v;
  61068. result.b = v;
  61069. }
  61070. else {
  61071. // sector 0 to 5
  61072. h /= 60;
  61073. var i = Math.floor(h);
  61074. // fractional part of h
  61075. var f = h - i;
  61076. var p = v * (1 - s);
  61077. var q = v * (1 - s * f);
  61078. var t = v * (1 - s * (1 - f));
  61079. switch (i) {
  61080. case 0:
  61081. result.r = v;
  61082. result.g = t;
  61083. result.b = p;
  61084. break;
  61085. case 1:
  61086. result.r = q;
  61087. result.g = v;
  61088. result.b = p;
  61089. break;
  61090. case 2:
  61091. result.r = p;
  61092. result.g = v;
  61093. result.b = t;
  61094. break;
  61095. case 3:
  61096. result.r = p;
  61097. result.g = q;
  61098. result.b = v;
  61099. break;
  61100. case 4:
  61101. result.r = t;
  61102. result.g = p;
  61103. result.b = v;
  61104. break;
  61105. default:
  61106. result.r = v;
  61107. result.g = p;
  61108. result.b = q;
  61109. break;
  61110. }
  61111. }
  61112. result.a = 1;
  61113. };
  61114. /**
  61115. * Returns a value clamped between min and max
  61116. * @param value The value to clamp
  61117. * @param min The minimum of value
  61118. * @param max The maximum of value
  61119. * @returns The clamped value.
  61120. */
  61121. ColorCurves.clamp = function (value, min, max) {
  61122. return Math.min(Math.max(value, min), max);
  61123. };
  61124. /**
  61125. * Clones the current color curve instance.
  61126. * @return The cloned curves
  61127. */
  61128. ColorCurves.prototype.clone = function () {
  61129. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  61130. };
  61131. /**
  61132. * Serializes the current color curve instance to a json representation.
  61133. * @return a JSON representation
  61134. */
  61135. ColorCurves.prototype.serialize = function () {
  61136. return BABYLON.SerializationHelper.Serialize(this);
  61137. };
  61138. /**
  61139. * Parses the color curve from a json representation.
  61140. * @param source the JSON source to parse
  61141. * @return The parsed curves
  61142. */
  61143. ColorCurves.Parse = function (source) {
  61144. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  61145. };
  61146. return ColorCurves;
  61147. }());
  61148. __decorate([
  61149. BABYLON.serialize()
  61150. ], ColorCurves.prototype, "_globalHue", void 0);
  61151. __decorate([
  61152. BABYLON.serialize()
  61153. ], ColorCurves.prototype, "_globalDensity", void 0);
  61154. __decorate([
  61155. BABYLON.serialize()
  61156. ], ColorCurves.prototype, "_globalSaturation", void 0);
  61157. __decorate([
  61158. BABYLON.serialize()
  61159. ], ColorCurves.prototype, "_globalExposure", void 0);
  61160. __decorate([
  61161. BABYLON.serialize()
  61162. ], ColorCurves.prototype, "_highlightsHue", void 0);
  61163. __decorate([
  61164. BABYLON.serialize()
  61165. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  61166. __decorate([
  61167. BABYLON.serialize()
  61168. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  61169. __decorate([
  61170. BABYLON.serialize()
  61171. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  61172. __decorate([
  61173. BABYLON.serialize()
  61174. ], ColorCurves.prototype, "_midtonesHue", void 0);
  61175. __decorate([
  61176. BABYLON.serialize()
  61177. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  61178. __decorate([
  61179. BABYLON.serialize()
  61180. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  61181. __decorate([
  61182. BABYLON.serialize()
  61183. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  61184. BABYLON.ColorCurves = ColorCurves;
  61185. })(BABYLON || (BABYLON = {}));
  61186. //# sourceMappingURL=babylon.colorCurves.js.map
  61187. var BABYLON;
  61188. (function (BABYLON) {
  61189. var Octree = (function () {
  61190. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  61191. if (maxDepth === void 0) { maxDepth = 2; }
  61192. this.maxDepth = maxDepth;
  61193. this.dynamicContent = new Array();
  61194. this._maxBlockCapacity = maxBlockCapacity || 64;
  61195. this._selectionContent = new BABYLON.SmartArray(1024);
  61196. this._creationFunc = creationFunc;
  61197. }
  61198. // Methods
  61199. Octree.prototype.update = function (worldMin, worldMax, entries) {
  61200. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  61201. };
  61202. Octree.prototype.addMesh = function (entry) {
  61203. for (var index = 0; index < this.blocks.length; index++) {
  61204. var block = this.blocks[index];
  61205. block.addEntry(entry);
  61206. }
  61207. };
  61208. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  61209. this._selectionContent.reset();
  61210. for (var index = 0; index < this.blocks.length; index++) {
  61211. var block = this.blocks[index];
  61212. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  61213. }
  61214. if (allowDuplicate) {
  61215. this._selectionContent.concat(this.dynamicContent);
  61216. }
  61217. else {
  61218. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  61219. }
  61220. return this._selectionContent;
  61221. };
  61222. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  61223. this._selectionContent.reset();
  61224. for (var index = 0; index < this.blocks.length; index++) {
  61225. var block = this.blocks[index];
  61226. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  61227. }
  61228. if (allowDuplicate) {
  61229. this._selectionContent.concat(this.dynamicContent);
  61230. }
  61231. else {
  61232. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  61233. }
  61234. return this._selectionContent;
  61235. };
  61236. Octree.prototype.intersectsRay = function (ray) {
  61237. this._selectionContent.reset();
  61238. for (var index = 0; index < this.blocks.length; index++) {
  61239. var block = this.blocks[index];
  61240. block.intersectsRay(ray, this._selectionContent);
  61241. }
  61242. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  61243. return this._selectionContent;
  61244. };
  61245. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  61246. target.blocks = new Array();
  61247. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  61248. // Segmenting space
  61249. for (var x = 0; x < 2; x++) {
  61250. for (var y = 0; y < 2; y++) {
  61251. for (var z = 0; z < 2; z++) {
  61252. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  61253. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  61254. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  61255. block.addEntries(entries);
  61256. target.blocks.push(block);
  61257. }
  61258. }
  61259. }
  61260. };
  61261. return Octree;
  61262. }());
  61263. Octree.CreationFuncForMeshes = function (entry, block) {
  61264. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  61265. block.entries.push(entry);
  61266. }
  61267. };
  61268. Octree.CreationFuncForSubMeshes = function (entry, block) {
  61269. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  61270. block.entries.push(entry);
  61271. }
  61272. };
  61273. BABYLON.Octree = Octree;
  61274. })(BABYLON || (BABYLON = {}));
  61275. //# sourceMappingURL=babylon.octree.js.map
  61276. var BABYLON;
  61277. (function (BABYLON) {
  61278. var OctreeBlock = (function () {
  61279. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  61280. this.entries = new Array();
  61281. this._boundingVectors = new Array();
  61282. this._capacity = capacity;
  61283. this._depth = depth;
  61284. this._maxDepth = maxDepth;
  61285. this._creationFunc = creationFunc;
  61286. this._minPoint = minPoint;
  61287. this._maxPoint = maxPoint;
  61288. this._boundingVectors.push(minPoint.clone());
  61289. this._boundingVectors.push(maxPoint.clone());
  61290. this._boundingVectors.push(minPoint.clone());
  61291. this._boundingVectors[2].x = maxPoint.x;
  61292. this._boundingVectors.push(minPoint.clone());
  61293. this._boundingVectors[3].y = maxPoint.y;
  61294. this._boundingVectors.push(minPoint.clone());
  61295. this._boundingVectors[4].z = maxPoint.z;
  61296. this._boundingVectors.push(maxPoint.clone());
  61297. this._boundingVectors[5].z = minPoint.z;
  61298. this._boundingVectors.push(maxPoint.clone());
  61299. this._boundingVectors[6].x = minPoint.x;
  61300. this._boundingVectors.push(maxPoint.clone());
  61301. this._boundingVectors[7].y = minPoint.y;
  61302. }
  61303. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  61304. // Property
  61305. get: function () {
  61306. return this._capacity;
  61307. },
  61308. enumerable: true,
  61309. configurable: true
  61310. });
  61311. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  61312. get: function () {
  61313. return this._minPoint;
  61314. },
  61315. enumerable: true,
  61316. configurable: true
  61317. });
  61318. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  61319. get: function () {
  61320. return this._maxPoint;
  61321. },
  61322. enumerable: true,
  61323. configurable: true
  61324. });
  61325. // Methods
  61326. OctreeBlock.prototype.addEntry = function (entry) {
  61327. if (this.blocks) {
  61328. for (var index = 0; index < this.blocks.length; index++) {
  61329. var block = this.blocks[index];
  61330. block.addEntry(entry);
  61331. }
  61332. return;
  61333. }
  61334. this._creationFunc(entry, this);
  61335. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  61336. this.createInnerBlocks();
  61337. }
  61338. };
  61339. OctreeBlock.prototype.addEntries = function (entries) {
  61340. for (var index = 0; index < entries.length; index++) {
  61341. var mesh = entries[index];
  61342. this.addEntry(mesh);
  61343. }
  61344. };
  61345. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  61346. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  61347. if (this.blocks) {
  61348. for (var index = 0; index < this.blocks.length; index++) {
  61349. var block = this.blocks[index];
  61350. block.select(frustumPlanes, selection, allowDuplicate);
  61351. }
  61352. return;
  61353. }
  61354. if (allowDuplicate) {
  61355. selection.concat(this.entries);
  61356. }
  61357. else {
  61358. selection.concatWithNoDuplicate(this.entries);
  61359. }
  61360. }
  61361. };
  61362. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  61363. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  61364. if (this.blocks) {
  61365. for (var index = 0; index < this.blocks.length; index++) {
  61366. var block = this.blocks[index];
  61367. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  61368. }
  61369. return;
  61370. }
  61371. if (allowDuplicate) {
  61372. selection.concat(this.entries);
  61373. }
  61374. else {
  61375. selection.concatWithNoDuplicate(this.entries);
  61376. }
  61377. }
  61378. };
  61379. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  61380. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  61381. if (this.blocks) {
  61382. for (var index = 0; index < this.blocks.length; index++) {
  61383. var block = this.blocks[index];
  61384. block.intersectsRay(ray, selection);
  61385. }
  61386. return;
  61387. }
  61388. selection.concatWithNoDuplicate(this.entries);
  61389. }
  61390. };
  61391. OctreeBlock.prototype.createInnerBlocks = function () {
  61392. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  61393. };
  61394. return OctreeBlock;
  61395. }());
  61396. BABYLON.OctreeBlock = OctreeBlock;
  61397. })(BABYLON || (BABYLON = {}));
  61398. //# sourceMappingURL=babylon.octreeBlock.js.map
  61399. var BABYLON;
  61400. (function (BABYLON) {
  61401. var SIMDVector3 = (function () {
  61402. function SIMDVector3() {
  61403. }
  61404. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  61405. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  61406. };
  61407. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  61408. var m = transformation.m;
  61409. var m0 = SIMD.Float32x4.load(m, 0);
  61410. var m1 = SIMD.Float32x4.load(m, 4);
  61411. var m2 = SIMD.Float32x4.load(m, 8);
  61412. var m3 = SIMD.Float32x4.load(m, 12);
  61413. 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));
  61414. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  61415. result.x = SIMD.Float32x4.extractLane(r, 0);
  61416. result.y = SIMD.Float32x4.extractLane(r, 1);
  61417. result.z = SIMD.Float32x4.extractLane(r, 2);
  61418. };
  61419. return SIMDVector3;
  61420. }());
  61421. var SIMDMatrix = (function () {
  61422. function SIMDMatrix() {
  61423. }
  61424. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  61425. var tm = this.m;
  61426. var om = other.m;
  61427. var m0 = SIMD.Float32x4.load(om, 0);
  61428. var m1 = SIMD.Float32x4.load(om, 4);
  61429. var m2 = SIMD.Float32x4.load(om, 8);
  61430. var m3 = SIMD.Float32x4.load(om, 12);
  61431. for (var i = 0; i < 16; i += 4) {
  61432. 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)))));
  61433. }
  61434. return this;
  61435. };
  61436. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  61437. var src = this.m;
  61438. var dest = other.m;
  61439. // Load the 4 rows
  61440. var src0 = SIMD.Float32x4.load(src, 0);
  61441. var src1 = SIMD.Float32x4.load(src, 4);
  61442. var src2 = SIMD.Float32x4.load(src, 8);
  61443. var src3 = SIMD.Float32x4.load(src, 12);
  61444. // Transpose the source matrix. Sort of. Not a true transpose operation
  61445. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  61446. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  61447. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  61448. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  61449. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  61450. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  61451. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  61452. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  61453. // This is a true transposition, but it will lead to an incorrect result
  61454. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  61455. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  61456. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  61457. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  61458. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  61459. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  61460. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  61461. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  61462. // ----
  61463. tmp1 = SIMD.Float32x4.mul(row2, row3);
  61464. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61465. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  61466. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  61467. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61468. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  61469. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  61470. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  61471. // ----
  61472. tmp1 = SIMD.Float32x4.mul(row1, row2);
  61473. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61474. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  61475. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  61476. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61477. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  61478. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  61479. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  61480. // ----
  61481. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  61482. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61483. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  61484. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  61485. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  61486. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61487. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  61488. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  61489. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  61490. // ----
  61491. tmp1 = SIMD.Float32x4.mul(row0, row1);
  61492. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61493. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  61494. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  61495. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61496. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  61497. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  61498. // ----
  61499. tmp1 = SIMD.Float32x4.mul(row0, row3);
  61500. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61501. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  61502. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  61503. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61504. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  61505. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  61506. // ----
  61507. tmp1 = SIMD.Float32x4.mul(row0, row2);
  61508. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  61509. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  61510. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  61511. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  61512. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  61513. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  61514. // Compute determinant
  61515. var det = SIMD.Float32x4.mul(row0, minor0);
  61516. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  61517. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  61518. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  61519. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  61520. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  61521. // These shuffles aren't necessary if the faulty transposition is done
  61522. // up at the top of this function.
  61523. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  61524. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  61525. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  61526. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  61527. // Compute final values by multiplying with 1/det
  61528. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  61529. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  61530. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  61531. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  61532. return this;
  61533. };
  61534. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  61535. var out = result.m;
  61536. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  61537. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  61538. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  61539. // cc.kmVec3Subtract(f, pCenter, pEye);
  61540. var f = SIMD.Float32x4.sub(center, eye);
  61541. // cc.kmVec3Normalize(f, f);
  61542. var tmp = SIMD.Float32x4.mul(f, f);
  61543. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61544. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61545. // cc.kmVec3Assign(up, pUp);
  61546. // cc.kmVec3Normalize(up, up);
  61547. tmp = SIMD.Float32x4.mul(up, up);
  61548. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61549. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61550. // cc.kmVec3Cross(s, f, up);
  61551. 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)));
  61552. // cc.kmVec3Normalize(s, s);
  61553. tmp = SIMD.Float32x4.mul(s, s);
  61554. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61555. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61556. // cc.kmVec3Cross(u, s, f);
  61557. 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)));
  61558. // cc.kmVec3Normalize(s, s);
  61559. tmp = SIMD.Float32x4.mul(s, s);
  61560. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  61561. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  61562. var zero = SIMD.Float32x4.splat(0.0);
  61563. s = SIMD.Float32x4.neg(s);
  61564. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  61565. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  61566. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  61567. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  61568. 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);
  61569. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  61570. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  61571. 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)))));
  61572. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  61573. 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)))));
  61574. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  61575. 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)))));
  61576. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  61577. 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)))));
  61578. };
  61579. return SIMDMatrix;
  61580. }());
  61581. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  61582. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  61583. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  61584. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  61585. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  61586. var SIMDHelper = (function () {
  61587. function SIMDHelper() {
  61588. }
  61589. Object.defineProperty(SIMDHelper, "IsEnabled", {
  61590. get: function () {
  61591. return SIMDHelper._isEnabled;
  61592. },
  61593. enumerable: true,
  61594. configurable: true
  61595. });
  61596. SIMDHelper.DisableSIMD = function () {
  61597. // Replace functions
  61598. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  61599. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  61600. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  61601. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  61602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  61603. SIMDHelper._isEnabled = false;
  61604. };
  61605. SIMDHelper.EnableSIMD = function () {
  61606. if (self.SIMD === undefined) {
  61607. return;
  61608. }
  61609. // check if polyfills needed
  61610. if (!self.Math.fround) {
  61611. self.Math.fround = (function (array) { return function (x) {
  61612. return array[0] = x, array[0];
  61613. }; })(new Float32Array(1));
  61614. }
  61615. if (!self.Math.imul) {
  61616. self.Math.imul = function (a, b) {
  61617. var ah = (a >>> 16) & 0xffff;
  61618. var al = a & 0xffff;
  61619. var bh = (b >>> 16) & 0xffff;
  61620. var bl = b & 0xffff;
  61621. // the shift by 0 fixes the sign on the high part
  61622. // the final |0 converts the unsigned value into a signed value
  61623. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  61624. };
  61625. }
  61626. // Replace functions
  61627. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  61628. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  61629. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  61630. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  61631. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  61632. SIMDHelper._isEnabled = true;
  61633. };
  61634. return SIMDHelper;
  61635. }());
  61636. SIMDHelper._isEnabled = false;
  61637. BABYLON.SIMDHelper = SIMDHelper;
  61638. })(BABYLON || (BABYLON = {}));
  61639. //# sourceMappingURL=babylon.math.SIMD.js.map
  61640. var BABYLON;
  61641. (function (BABYLON) {
  61642. var VRDistortionCorrectionPostProcess = (function (_super) {
  61643. __extends(VRDistortionCorrectionPostProcess, _super);
  61644. //ANY
  61645. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  61646. var _this = _super.call(this, name, "vrDistortionCorrection", [
  61647. 'LensCenter',
  61648. 'Scale',
  61649. 'ScaleIn',
  61650. 'HmdWarpParam'
  61651. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  61652. _this._isRightEye = isRightEye;
  61653. _this._distortionFactors = vrMetrics.distortionK;
  61654. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  61655. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  61656. _this.onSizeChangedObservable.add(function () {
  61657. _this.aspectRatio = _this.width * .5 / _this.height;
  61658. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  61659. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  61660. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  61661. });
  61662. _this.onApplyObservable.add(function (effect) {
  61663. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  61664. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  61665. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  61666. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  61667. });
  61668. return _this;
  61669. }
  61670. return VRDistortionCorrectionPostProcess;
  61671. }(BABYLON.PostProcess));
  61672. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  61673. })(BABYLON || (BABYLON = {}));
  61674. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  61675. var BABYLON;
  61676. (function (BABYLON) {
  61677. var AnaglyphPostProcess = (function (_super) {
  61678. __extends(AnaglyphPostProcess, _super);
  61679. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  61680. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  61681. _this._passedProcess = rigCameras[0]._rigPostProcess;
  61682. _this.onApplyObservable.add(function (effect) {
  61683. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  61684. });
  61685. return _this;
  61686. }
  61687. return AnaglyphPostProcess;
  61688. }(BABYLON.PostProcess));
  61689. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  61690. })(BABYLON || (BABYLON = {}));
  61691. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  61692. var BABYLON;
  61693. (function (BABYLON) {
  61694. var StereoscopicInterlacePostProcess = (function (_super) {
  61695. __extends(StereoscopicInterlacePostProcess, _super);
  61696. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  61697. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  61698. _this._passedProcess = rigCameras[0]._rigPostProcess;
  61699. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  61700. _this.onSizeChangedObservable.add(function () {
  61701. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  61702. });
  61703. _this.onApplyObservable.add(function (effect) {
  61704. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  61705. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  61706. });
  61707. return _this;
  61708. }
  61709. return StereoscopicInterlacePostProcess;
  61710. }(BABYLON.PostProcess));
  61711. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  61712. })(BABYLON || (BABYLON = {}));
  61713. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  61714. var BABYLON;
  61715. (function (BABYLON) {
  61716. var FreeCameraDeviceOrientationInput = (function () {
  61717. function FreeCameraDeviceOrientationInput() {
  61718. var _this = this;
  61719. this._screenOrientationAngle = 0;
  61720. this._screenQuaternion = new BABYLON.Quaternion();
  61721. this._alpha = 0;
  61722. this._beta = 0;
  61723. this._gamma = 0;
  61724. this._orientationChanged = function () {
  61725. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  61726. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  61727. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  61728. };
  61729. this._deviceOrientation = function (evt) {
  61730. _this._alpha = evt.alpha;
  61731. _this._beta = evt.beta;
  61732. _this._gamma = evt.gamma;
  61733. };
  61734. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  61735. this._orientationChanged();
  61736. }
  61737. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  61738. get: function () {
  61739. return this._camera;
  61740. },
  61741. set: function (camera) {
  61742. this._camera = camera;
  61743. if (!this._camera.rotationQuaternion)
  61744. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  61745. },
  61746. enumerable: true,
  61747. configurable: true
  61748. });
  61749. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  61750. window.addEventListener("orientationchange", this._orientationChanged);
  61751. window.addEventListener("deviceorientation", this._deviceOrientation);
  61752. //In certain cases, the attach control is called AFTER orientation was changed,
  61753. //So this is needed.
  61754. this._orientationChanged();
  61755. };
  61756. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  61757. window.removeEventListener("orientationchange", this._orientationChanged);
  61758. window.removeEventListener("deviceorientation", this._deviceOrientation);
  61759. };
  61760. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  61761. //if no device orientation provided, don't update the rotation.
  61762. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  61763. if (!this._alpha)
  61764. return;
  61765. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  61766. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  61767. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  61768. //Mirror on XY Plane
  61769. this._camera.rotationQuaternion.z *= -1;
  61770. this._camera.rotationQuaternion.w *= -1;
  61771. };
  61772. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  61773. return "FreeCameraDeviceOrientationInput";
  61774. };
  61775. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  61776. return "deviceOrientation";
  61777. };
  61778. return FreeCameraDeviceOrientationInput;
  61779. }());
  61780. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  61781. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  61782. })(BABYLON || (BABYLON = {}));
  61783. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  61784. var BABYLON;
  61785. (function (BABYLON) {
  61786. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  61787. function ArcRotateCameraVRDeviceOrientationInput() {
  61788. this.alphaCorrection = 1;
  61789. this.betaCorrection = 1;
  61790. this.gammaCorrection = 1;
  61791. this._alpha = 0;
  61792. this._beta = 0;
  61793. this._gamma = 0;
  61794. this._dirty = false;
  61795. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  61796. }
  61797. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  61798. this.camera.attachControl(element, noPreventDefault);
  61799. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  61800. };
  61801. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  61802. var camera = this.camera;
  61803. this._alpha = +evt.alpha | 0;
  61804. this._beta = +evt.beta | 0;
  61805. this._gamma = +evt.gamma | 0;
  61806. this._dirty = true;
  61807. };
  61808. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  61809. if (this._dirty) {
  61810. this._dirty = false;
  61811. if (this._gamma < 0) {
  61812. this._gamma = 180 + this._gamma;
  61813. }
  61814. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  61815. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  61816. }
  61817. };
  61818. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  61819. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  61820. };
  61821. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  61822. return "ArcRotateCameraVRDeviceOrientationInput";
  61823. };
  61824. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  61825. return "VRDeviceOrientation";
  61826. };
  61827. return ArcRotateCameraVRDeviceOrientationInput;
  61828. }());
  61829. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  61830. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  61831. })(BABYLON || (BABYLON = {}));
  61832. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  61833. var BABYLON;
  61834. (function (BABYLON) {
  61835. var VRCameraMetrics = (function () {
  61836. function VRCameraMetrics() {
  61837. this.compensateDistortion = true;
  61838. }
  61839. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  61840. get: function () {
  61841. return this.hResolution / (2 * this.vResolution);
  61842. },
  61843. enumerable: true,
  61844. configurable: true
  61845. });
  61846. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  61847. get: function () {
  61848. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  61849. },
  61850. enumerable: true,
  61851. configurable: true
  61852. });
  61853. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  61854. get: function () {
  61855. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61856. var h = (4 * meters) / this.hScreenSize;
  61857. return BABYLON.Matrix.Translation(h, 0, 0);
  61858. },
  61859. enumerable: true,
  61860. configurable: true
  61861. });
  61862. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  61863. get: function () {
  61864. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  61865. var h = (4 * meters) / this.hScreenSize;
  61866. return BABYLON.Matrix.Translation(-h, 0, 0);
  61867. },
  61868. enumerable: true,
  61869. configurable: true
  61870. });
  61871. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  61872. get: function () {
  61873. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  61874. },
  61875. enumerable: true,
  61876. configurable: true
  61877. });
  61878. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  61879. get: function () {
  61880. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  61881. },
  61882. enumerable: true,
  61883. configurable: true
  61884. });
  61885. VRCameraMetrics.GetDefault = function () {
  61886. var result = new VRCameraMetrics();
  61887. result.hResolution = 1280;
  61888. result.vResolution = 800;
  61889. result.hScreenSize = 0.149759993;
  61890. result.vScreenSize = 0.0935999975;
  61891. result.vScreenCenter = 0.0467999987;
  61892. result.eyeToScreenDistance = 0.0410000011;
  61893. result.lensSeparationDistance = 0.0635000020;
  61894. result.interpupillaryDistance = 0.0640000030;
  61895. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  61896. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  61897. result.postProcessScaleFactor = 1.714605507808412;
  61898. result.lensCenterOffset = 0.151976421;
  61899. return result;
  61900. };
  61901. return VRCameraMetrics;
  61902. }());
  61903. BABYLON.VRCameraMetrics = VRCameraMetrics;
  61904. })(BABYLON || (BABYLON = {}));
  61905. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  61906. var BABYLON;
  61907. (function (BABYLON) {
  61908. var WebVRFreeCamera = (function (_super) {
  61909. __extends(WebVRFreeCamera, _super);
  61910. function WebVRFreeCamera(name, position, scene, webVROptions) {
  61911. if (webVROptions === void 0) { webVROptions = {}; }
  61912. var _this = _super.call(this, name, position, scene) || this;
  61913. _this.webVROptions = webVROptions;
  61914. _this._vrDevice = null;
  61915. _this.rawPose = null;
  61916. _this._vrEnabled = false;
  61917. _this._specsVersion = 1.1;
  61918. _this._attached = false;
  61919. _this._positionOffset = BABYLON.Vector3.Zero();
  61920. _this._descendants = [];
  61921. _this.devicePosition = BABYLON.Vector3.Zero();
  61922. _this.deviceScaleFactor = 1;
  61923. _this.controllers = [];
  61924. _this.nonVRControllers = [];
  61925. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  61926. //legacy support - the compensation boolean was removed.
  61927. if (arguments.length === 5) {
  61928. _this.webVROptions = arguments[4];
  61929. }
  61930. // default webVR options
  61931. if (_this.webVROptions.trackPosition == undefined) {
  61932. _this.webVROptions.trackPosition = true;
  61933. }
  61934. if (_this.webVROptions.controllerMeshes == undefined) {
  61935. _this.webVROptions.controllerMeshes = true;
  61936. }
  61937. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  61938. _this.webVROptions.defaultLightningOnControllers = true;
  61939. }
  61940. _this.rotationQuaternion = new BABYLON.Quaternion();
  61941. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  61942. if (_this.webVROptions && _this.webVROptions.positionScale) {
  61943. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  61944. }
  61945. //enable VR
  61946. _this.getEngine().initWebVR();
  61947. //check specs version
  61948. if (!window.VRFrameData) {
  61949. _this._specsVersion = 1.0;
  61950. _this._frameData = {};
  61951. }
  61952. else {
  61953. _this._frameData = new VRFrameData();
  61954. }
  61955. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  61956. if (!device) {
  61957. return;
  61958. }
  61959. _this._vrEnabled = true;
  61960. _this._vrDevice = device;
  61961. //reset the rig parameters.
  61962. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  61963. if (_this._attached) {
  61964. _this.getEngine().enableVR(_this._vrDevice);
  61965. }
  61966. });
  61967. // try to attach the controllers, if found.
  61968. _this.initControllers();
  61969. /**
  61970. * The idea behind the following lines:
  61971. * objects that have the camera as parent should actually have the rig cameras as a parent.
  61972. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  61973. * the second will not show it correctly.
  61974. *
  61975. * To solve this - each object that has the camera as parent will be added to a protected array.
  61976. * When the rig camera renders, it will take this array and set all of those to be its children.
  61977. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  61978. * Amazing!
  61979. */
  61980. scene.onBeforeCameraRenderObservable.add(function (camera) {
  61981. if (camera.parent === _this && _this.rigParenting) {
  61982. _this._descendants = _this.getDescendants(true, function (n) {
  61983. // don't take the cameras or the controllers!
  61984. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  61985. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  61986. return !isController && !isRigCamera;
  61987. });
  61988. _this._descendants.forEach(function (node) {
  61989. node.parent = camera;
  61990. });
  61991. }
  61992. });
  61993. scene.onAfterCameraRenderObservable.add(function (camera) {
  61994. if (camera.parent === _this && _this.rigParenting) {
  61995. _this._descendants.forEach(function (node) {
  61996. node.parent = _this;
  61997. });
  61998. }
  61999. });
  62000. return _this;
  62001. }
  62002. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  62003. set: function (callback) {
  62004. this._onControllersAttached = callback;
  62005. // after setting - if the controllers are already set, execute the callback.
  62006. if (this.controllers.length >= 2) {
  62007. callback(this.controllers);
  62008. }
  62009. },
  62010. enumerable: true,
  62011. configurable: true
  62012. });
  62013. Object.defineProperty(WebVRFreeCamera.prototype, "onNonVRControllerAttached", {
  62014. set: function (callback) {
  62015. this._onNonVRControllerAttached = callback;
  62016. this.nonVRControllers.forEach(function (controller) {
  62017. callback(controller);
  62018. });
  62019. },
  62020. enumerable: true,
  62021. configurable: true
  62022. });
  62023. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  62024. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  62025. var gp = _a[_i];
  62026. if (gp.hand === name) {
  62027. return gp;
  62028. }
  62029. }
  62030. return undefined;
  62031. };
  62032. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  62033. get: function () {
  62034. if (!this._leftController) {
  62035. this._leftController = this.getControllerByName("left");
  62036. }
  62037. return this._leftController;
  62038. },
  62039. enumerable: true,
  62040. configurable: true
  62041. });
  62042. ;
  62043. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  62044. get: function () {
  62045. if (!this._rightController) {
  62046. this._rightController = this.getControllerByName("right");
  62047. }
  62048. return this._rightController;
  62049. },
  62050. enumerable: true,
  62051. configurable: true
  62052. });
  62053. ;
  62054. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  62055. if (length === void 0) { length = 100; }
  62056. if (this.leftCamera) {
  62057. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  62058. }
  62059. else {
  62060. return _super.prototype.getForwardRay.call(this, length);
  62061. }
  62062. };
  62063. WebVRFreeCamera.prototype._checkInputs = function () {
  62064. if (this._vrEnabled) {
  62065. if (this._specsVersion === 1.1) {
  62066. this._vrDevice.getFrameData(this._frameData);
  62067. }
  62068. else {
  62069. //backwards comp
  62070. var pose = this._vrDevice.getPose();
  62071. this._frameData.pose = pose;
  62072. // calculate view and projection matrix
  62073. }
  62074. this.updateFromDevice(this._frameData.pose);
  62075. }
  62076. _super.prototype._checkInputs.call(this);
  62077. };
  62078. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  62079. if (poseData && poseData.orientation) {
  62080. this.rawPose = poseData;
  62081. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  62082. if (this.getScene().useRightHandedSystem) {
  62083. this.deviceRotationQuaternion.z *= -1;
  62084. this.deviceRotationQuaternion.w *= -1;
  62085. }
  62086. if (this.webVROptions.trackPosition && this.rawPose.position) {
  62087. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  62088. if (this.getScene().useRightHandedSystem) {
  62089. this.devicePosition.z *= -1;
  62090. }
  62091. }
  62092. }
  62093. };
  62094. /**
  62095. * WebVR's attach control will start broadcasting frames to the device.
  62096. * Note that in certain browsers (chrome for example) this function must be called
  62097. * within a user-interaction callback. Example:
  62098. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  62099. *
  62100. * @param {HTMLElement} element
  62101. * @param {boolean} [noPreventDefault]
  62102. *
  62103. * @memberOf WebVRFreeCamera
  62104. */
  62105. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  62106. _super.prototype.attachControl.call(this, element, noPreventDefault);
  62107. this._attached = true;
  62108. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  62109. if (this._vrEnabled) {
  62110. this.getEngine().enableVR(this._vrDevice);
  62111. }
  62112. };
  62113. WebVRFreeCamera.prototype.detachControl = function (element) {
  62114. _super.prototype.detachControl.call(this, element);
  62115. this._vrEnabled = false;
  62116. this._attached = false;
  62117. this.getEngine().disableVR();
  62118. };
  62119. WebVRFreeCamera.prototype.getClassName = function () {
  62120. return "WebVRFreeCamera";
  62121. };
  62122. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  62123. //uses the vrDisplay's "resetPose()".
  62124. //pitch and roll won't be affected.
  62125. this._vrDevice.resetPose();
  62126. };
  62127. WebVRFreeCamera.prototype._updateRigCameras = function () {
  62128. var camLeft = this._rigCameras[0];
  62129. var camRight = this._rigCameras[1];
  62130. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  62131. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  62132. camLeft.position.copyFrom(this.devicePosition);
  62133. camRight.position.copyFrom(this.devicePosition);
  62134. };
  62135. /**
  62136. * This function is called by the two RIG cameras.
  62137. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  62138. */
  62139. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  62140. var _this = this;
  62141. //WebVR 1.0
  62142. if (this._cameraRigParams["specs"] === 1.0) {
  62143. this._updateCameraRotationMatrix();
  62144. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  62145. // Computing target and final matrix
  62146. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  62147. if (this.getScene().useRightHandedSystem) {
  62148. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  62149. }
  62150. else {
  62151. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  62152. }
  62153. //now move the eye in the right direction
  62154. var eyeParams = this._cameraRigParams["eyeParameters"];
  62155. var offset = eyeParams.offset;
  62156. // it will actually always be 0, but just in case
  62157. if (this.getScene().useRightHandedSystem) {
  62158. offset[2] *= -1;
  62159. }
  62160. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  62161. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  62162. }
  62163. else {
  62164. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  62165. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  62166. if (!this.getScene().useRightHandedSystem) {
  62167. [2, 6, 8, 9, 14].forEach(function (num) {
  62168. _this._webvrViewMatrix.m[num] *= -1;
  62169. });
  62170. }
  62171. // update the camera rotation matrix
  62172. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  62173. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  62174. // Computing target and final matrix
  62175. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  62176. }
  62177. var parentCamera = this._cameraRigParams["parentCamera"];
  62178. // should the view matrix be updated with scale and position offset?
  62179. if (parentCamera.deviceScaleFactor !== 1) {
  62180. this._webvrViewMatrix.invert();
  62181. // scale the position, if set
  62182. if (parentCamera.deviceScaleFactor) {
  62183. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  62184. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  62185. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  62186. }
  62187. this._webvrViewMatrix.invert();
  62188. }
  62189. return this._webvrViewMatrix;
  62190. };
  62191. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  62192. var _this = this;
  62193. if (this._cameraRigParams["specs"] === 1.0) {
  62194. var eyeParams = this._cameraRigParams["eyeParameters"];
  62195. // deprecated!!
  62196. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  62197. }
  62198. else {
  62199. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  62200. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  62201. //babylon compatible matrix
  62202. if (!this.getScene().useRightHandedSystem) {
  62203. [8, 9, 10, 11].forEach(function (num) {
  62204. _this._projectionMatrix.m[num] *= -1;
  62205. });
  62206. }
  62207. }
  62208. return this._projectionMatrix;
  62209. };
  62210. WebVRFreeCamera.prototype.initControllers = function () {
  62211. var _this = this;
  62212. this.controllers = [];
  62213. new BABYLON.Gamepads(function (gp) {
  62214. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  62215. var webVrController = gp;
  62216. if (_this.webVROptions.controllerMeshes) {
  62217. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  62218. if (_this.webVROptions.defaultLightningOnControllers) {
  62219. if (!_this._lightOnControllers) {
  62220. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  62221. }
  62222. loadedMesh.getChildren().forEach(function (mesh) {
  62223. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  62224. });
  62225. }
  62226. });
  62227. }
  62228. webVrController.attachToPoseControlledCamera(_this);
  62229. // since this is async - sanity check. Is the controller already stored?
  62230. if (_this.controllers.indexOf(webVrController) === -1) {
  62231. //add to the controllers array
  62232. _this.controllers.push(webVrController);
  62233. //did we find enough controllers? Great! let the developer know.
  62234. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  62235. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  62236. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  62237. // So we're overriding setting left & right manually to be sure
  62238. var firstViveWandDetected = false;
  62239. for (var i = 0; i < _this.controllers.length; i++) {
  62240. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  62241. if (!firstViveWandDetected) {
  62242. firstViveWandDetected = true;
  62243. _this.controllers[i].hand = "left";
  62244. }
  62245. else {
  62246. _this.controllers[i].hand = "right";
  62247. }
  62248. }
  62249. }
  62250. _this._onControllersAttached(_this.controllers);
  62251. }
  62252. }
  62253. }
  62254. else {
  62255. _this.nonVRControllers.push(gp);
  62256. if (_this._onNonVRControllerAttached) {
  62257. _this._onNonVRControllerAttached(gp);
  62258. }
  62259. }
  62260. });
  62261. };
  62262. return WebVRFreeCamera;
  62263. }(BABYLON.FreeCamera));
  62264. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  62265. })(BABYLON || (BABYLON = {}));
  62266. //# sourceMappingURL=babylon.webVRCamera.js.map
  62267. /// <reference path="babylon.freeCamera.ts" />
  62268. var BABYLON;
  62269. (function (BABYLON) {
  62270. // We're mainly based on the logic defined into the FreeCamera code
  62271. var DeviceOrientationCamera = (function (_super) {
  62272. __extends(DeviceOrientationCamera, _super);
  62273. function DeviceOrientationCamera(name, position, scene) {
  62274. var _this = _super.call(this, name, position, scene) || this;
  62275. _this._quaternionCache = new BABYLON.Quaternion();
  62276. _this.inputs.addDeviceOrientation();
  62277. return _this;
  62278. }
  62279. DeviceOrientationCamera.prototype.getClassName = function () {
  62280. return "DeviceOrientationCamera";
  62281. };
  62282. DeviceOrientationCamera.prototype._checkInputs = function () {
  62283. _super.prototype._checkInputs.call(this);
  62284. this._quaternionCache.copyFrom(this.rotationQuaternion);
  62285. if (this._initialQuaternion) {
  62286. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  62287. }
  62288. };
  62289. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  62290. var _this = this;
  62291. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  62292. //can only work if this camera has a rotation quaternion already.
  62293. if (!this.rotationQuaternion)
  62294. return;
  62295. if (!this._initialQuaternion) {
  62296. this._initialQuaternion = new BABYLON.Quaternion();
  62297. }
  62298. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  62299. ['x', 'y', 'z'].forEach(function (axisName) {
  62300. if (!axis[axisName]) {
  62301. _this._initialQuaternion[axisName] = 0;
  62302. }
  62303. else {
  62304. _this._initialQuaternion[axisName] *= -1;
  62305. }
  62306. });
  62307. this._initialQuaternion.normalize();
  62308. //force rotation update
  62309. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  62310. };
  62311. return DeviceOrientationCamera;
  62312. }(BABYLON.FreeCamera));
  62313. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  62314. })(BABYLON || (BABYLON = {}));
  62315. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  62316. var BABYLON;
  62317. (function (BABYLON) {
  62318. var VRDeviceOrientationFreeCamera = (function (_super) {
  62319. __extends(VRDeviceOrientationFreeCamera, _super);
  62320. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  62321. if (compensateDistortion === void 0) { compensateDistortion = true; }
  62322. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  62323. var _this = _super.call(this, name, position, scene) || this;
  62324. vrCameraMetrics.compensateDistortion = compensateDistortion;
  62325. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  62326. return _this;
  62327. }
  62328. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  62329. return "VRDeviceOrientationFreeCamera";
  62330. };
  62331. return VRDeviceOrientationFreeCamera;
  62332. }(BABYLON.DeviceOrientationCamera));
  62333. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  62334. var VRDeviceOrientationGamepadCamera = (function (_super) {
  62335. __extends(VRDeviceOrientationGamepadCamera, _super);
  62336. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  62337. if (compensateDistortion === void 0) { compensateDistortion = true; }
  62338. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  62339. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  62340. _this.inputs.addGamepad();
  62341. return _this;
  62342. }
  62343. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  62344. return "VRDeviceOrientationGamepadCamera";
  62345. };
  62346. return VRDeviceOrientationGamepadCamera;
  62347. }(VRDeviceOrientationFreeCamera));
  62348. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  62349. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  62350. __extends(VRDeviceOrientationArcRotateCamera, _super);
  62351. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  62352. if (compensateDistortion === void 0) { compensateDistortion = true; }
  62353. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  62354. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  62355. vrCameraMetrics.compensateDistortion = compensateDistortion;
  62356. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  62357. _this.inputs.addVRDeviceOrientation();
  62358. return _this;
  62359. }
  62360. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  62361. return "VRDeviceOrientationArcRotateCamera";
  62362. };
  62363. return VRDeviceOrientationArcRotateCamera;
  62364. }(BABYLON.ArcRotateCamera));
  62365. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  62366. })(BABYLON || (BABYLON = {}));
  62367. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  62368. /// <reference path="babylon.freeCamera.ts" />
  62369. /// <reference path="babylon.arcRotateCamera.ts" />
  62370. /// <reference path="babylon.gamepadCamera.ts" />
  62371. /// <reference path="babylon.universalCamera.ts" />
  62372. var BABYLON;
  62373. (function (BABYLON) {
  62374. var AnaglyphFreeCamera = (function (_super) {
  62375. __extends(AnaglyphFreeCamera, _super);
  62376. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  62377. var _this = _super.call(this, name, position, scene) || this;
  62378. _this.interaxialDistance = interaxialDistance;
  62379. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62380. return _this;
  62381. }
  62382. AnaglyphFreeCamera.prototype.getClassName = function () {
  62383. return "AnaglyphFreeCamera";
  62384. };
  62385. return AnaglyphFreeCamera;
  62386. }(BABYLON.FreeCamera));
  62387. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  62388. var AnaglyphArcRotateCamera = (function (_super) {
  62389. __extends(AnaglyphArcRotateCamera, _super);
  62390. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  62391. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  62392. _this.interaxialDistance = interaxialDistance;
  62393. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62394. return _this;
  62395. }
  62396. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  62397. return "AnaglyphArcRotateCamera";
  62398. };
  62399. return AnaglyphArcRotateCamera;
  62400. }(BABYLON.ArcRotateCamera));
  62401. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  62402. var AnaglyphGamepadCamera = (function (_super) {
  62403. __extends(AnaglyphGamepadCamera, _super);
  62404. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  62405. var _this = _super.call(this, name, position, scene) || this;
  62406. _this.interaxialDistance = interaxialDistance;
  62407. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62408. return _this;
  62409. }
  62410. AnaglyphGamepadCamera.prototype.getClassName = function () {
  62411. return "AnaglyphGamepadCamera";
  62412. };
  62413. return AnaglyphGamepadCamera;
  62414. }(BABYLON.GamepadCamera));
  62415. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  62416. var AnaglyphUniversalCamera = (function (_super) {
  62417. __extends(AnaglyphUniversalCamera, _super);
  62418. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  62419. var _this = _super.call(this, name, position, scene) || this;
  62420. _this.interaxialDistance = interaxialDistance;
  62421. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  62422. return _this;
  62423. }
  62424. AnaglyphUniversalCamera.prototype.getClassName = function () {
  62425. return "AnaglyphUniversalCamera";
  62426. };
  62427. return AnaglyphUniversalCamera;
  62428. }(BABYLON.UniversalCamera));
  62429. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  62430. var StereoscopicFreeCamera = (function (_super) {
  62431. __extends(StereoscopicFreeCamera, _super);
  62432. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  62433. var _this = _super.call(this, name, position, scene) || this;
  62434. _this.interaxialDistance = interaxialDistance;
  62435. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62436. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62437. return _this;
  62438. }
  62439. StereoscopicFreeCamera.prototype.getClassName = function () {
  62440. return "StereoscopicFreeCamera";
  62441. };
  62442. return StereoscopicFreeCamera;
  62443. }(BABYLON.FreeCamera));
  62444. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  62445. var StereoscopicArcRotateCamera = (function (_super) {
  62446. __extends(StereoscopicArcRotateCamera, _super);
  62447. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  62448. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  62449. _this.interaxialDistance = interaxialDistance;
  62450. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62451. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62452. return _this;
  62453. }
  62454. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  62455. return "StereoscopicArcRotateCamera";
  62456. };
  62457. return StereoscopicArcRotateCamera;
  62458. }(BABYLON.ArcRotateCamera));
  62459. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  62460. var StereoscopicGamepadCamera = (function (_super) {
  62461. __extends(StereoscopicGamepadCamera, _super);
  62462. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  62463. var _this = _super.call(this, name, position, scene) || this;
  62464. _this.interaxialDistance = interaxialDistance;
  62465. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62466. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62467. return _this;
  62468. }
  62469. StereoscopicGamepadCamera.prototype.getClassName = function () {
  62470. return "StereoscopicGamepadCamera";
  62471. };
  62472. return StereoscopicGamepadCamera;
  62473. }(BABYLON.GamepadCamera));
  62474. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  62475. var StereoscopicUniversalCamera = (function (_super) {
  62476. __extends(StereoscopicUniversalCamera, _super);
  62477. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  62478. var _this = _super.call(this, name, position, scene) || this;
  62479. _this.interaxialDistance = interaxialDistance;
  62480. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  62481. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  62482. return _this;
  62483. }
  62484. StereoscopicUniversalCamera.prototype.getClassName = function () {
  62485. return "StereoscopicUniversalCamera";
  62486. };
  62487. return StereoscopicUniversalCamera;
  62488. }(BABYLON.UniversalCamera));
  62489. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  62490. })(BABYLON || (BABYLON = {}));
  62491. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  62492. // Mainly based on these 2 articles :
  62493. // 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
  62494. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  62495. var BABYLON;
  62496. (function (BABYLON) {
  62497. var JoystickAxis;
  62498. (function (JoystickAxis) {
  62499. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  62500. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  62501. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  62502. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  62503. var VirtualJoystick = (function () {
  62504. function VirtualJoystick(leftJoystick) {
  62505. var _this = this;
  62506. if (leftJoystick) {
  62507. this._leftJoystick = true;
  62508. }
  62509. else {
  62510. this._leftJoystick = false;
  62511. }
  62512. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  62513. VirtualJoystick._globalJoystickIndex++;
  62514. // By default left & right arrow keys are moving the X
  62515. // and up & down keys are moving the Y
  62516. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  62517. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  62518. this.reverseLeftRight = false;
  62519. this.reverseUpDown = false;
  62520. // collections of pointers
  62521. this._touches = new BABYLON.StringDictionary();
  62522. this.deltaPosition = BABYLON.Vector3.Zero();
  62523. this._joystickSensibility = 25;
  62524. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  62525. this._rotationSpeed = 25;
  62526. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  62527. this._rotateOnAxisRelativeToMesh = false;
  62528. this._onResize = function (evt) {
  62529. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  62530. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  62531. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  62532. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  62533. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  62534. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  62535. };
  62536. // injecting a canvas element on top of the canvas 3D game
  62537. if (!VirtualJoystick.vjCanvas) {
  62538. window.addEventListener("resize", this._onResize, false);
  62539. VirtualJoystick.vjCanvas = document.createElement("canvas");
  62540. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  62541. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  62542. VirtualJoystick.vjCanvas.width = window.innerWidth;
  62543. VirtualJoystick.vjCanvas.height = window.innerHeight;
  62544. VirtualJoystick.vjCanvas.style.width = "100%";
  62545. VirtualJoystick.vjCanvas.style.height = "100%";
  62546. VirtualJoystick.vjCanvas.style.position = "absolute";
  62547. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  62548. VirtualJoystick.vjCanvas.style.top = "0px";
  62549. VirtualJoystick.vjCanvas.style.left = "0px";
  62550. VirtualJoystick.vjCanvas.style.zIndex = "5";
  62551. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  62552. // Support for jQuery PEP polyfill
  62553. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  62554. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  62555. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  62556. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  62557. document.body.appendChild(VirtualJoystick.vjCanvas);
  62558. }
  62559. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  62560. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  62561. this.pressed = false;
  62562. // default joystick color
  62563. this._joystickColor = "cyan";
  62564. this._joystickPointerID = -1;
  62565. // current joystick position
  62566. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  62567. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  62568. // origin joystick position
  62569. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  62570. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  62571. this._onPointerDownHandlerRef = function (evt) {
  62572. _this._onPointerDown(evt);
  62573. };
  62574. this._onPointerMoveHandlerRef = function (evt) {
  62575. _this._onPointerMove(evt);
  62576. };
  62577. this._onPointerOutHandlerRef = function (evt) {
  62578. _this._onPointerUp(evt);
  62579. };
  62580. this._onPointerUpHandlerRef = function (evt) {
  62581. _this._onPointerUp(evt);
  62582. };
  62583. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  62584. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  62585. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  62586. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  62587. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  62588. evt.preventDefault(); // Disables system menu
  62589. }, false);
  62590. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  62591. }
  62592. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  62593. this._joystickSensibility = newJoystickSensibility;
  62594. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  62595. };
  62596. VirtualJoystick.prototype._onPointerDown = function (e) {
  62597. var positionOnScreenCondition;
  62598. e.preventDefault();
  62599. if (this._leftJoystick === true) {
  62600. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  62601. }
  62602. else {
  62603. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  62604. }
  62605. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  62606. // First contact will be dedicated to the virtual joystick
  62607. this._joystickPointerID = e.pointerId;
  62608. this._joystickPointerStartPos.x = e.clientX;
  62609. this._joystickPointerStartPos.y = e.clientY;
  62610. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  62611. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  62612. this._deltaJoystickVector.x = 0;
  62613. this._deltaJoystickVector.y = 0;
  62614. this.pressed = true;
  62615. this._touches.add(e.pointerId.toString(), e);
  62616. }
  62617. else {
  62618. // You can only trigger the action buttons with a joystick declared
  62619. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  62620. this._action();
  62621. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  62622. }
  62623. }
  62624. };
  62625. VirtualJoystick.prototype._onPointerMove = function (e) {
  62626. // If the current pointer is the one associated to the joystick (first touch contact)
  62627. if (this._joystickPointerID == e.pointerId) {
  62628. this._joystickPointerPos.x = e.clientX;
  62629. this._joystickPointerPos.y = e.clientY;
  62630. this._deltaJoystickVector = this._joystickPointerPos.clone();
  62631. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  62632. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  62633. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  62634. switch (this._axisTargetedByLeftAndRight) {
  62635. case JoystickAxis.X:
  62636. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  62637. break;
  62638. case JoystickAxis.Y:
  62639. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  62640. break;
  62641. case JoystickAxis.Z:
  62642. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  62643. break;
  62644. }
  62645. var directionUpDown = this.reverseUpDown ? 1 : -1;
  62646. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  62647. switch (this._axisTargetedByUpAndDown) {
  62648. case JoystickAxis.X:
  62649. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  62650. break;
  62651. case JoystickAxis.Y:
  62652. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  62653. break;
  62654. case JoystickAxis.Z:
  62655. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  62656. break;
  62657. }
  62658. }
  62659. else {
  62660. var data = this._touches.get(e.pointerId.toString());
  62661. if (data) {
  62662. data.x = e.clientX;
  62663. data.y = e.clientY;
  62664. }
  62665. }
  62666. };
  62667. VirtualJoystick.prototype._onPointerUp = function (e) {
  62668. if (this._joystickPointerID == e.pointerId) {
  62669. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  62670. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  62671. this._joystickPointerID = -1;
  62672. this.pressed = false;
  62673. }
  62674. else {
  62675. var touch = this._touches.get(e.pointerId.toString());
  62676. if (touch) {
  62677. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  62678. }
  62679. }
  62680. this._deltaJoystickVector.x = 0;
  62681. this._deltaJoystickVector.y = 0;
  62682. this._touches.remove(e.pointerId.toString());
  62683. };
  62684. /**
  62685. * Change the color of the virtual joystick
  62686. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  62687. */
  62688. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  62689. this._joystickColor = newColor;
  62690. };
  62691. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  62692. this._action = action;
  62693. };
  62694. // Define which axis you'd like to control for left & right
  62695. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  62696. switch (axis) {
  62697. case JoystickAxis.X:
  62698. case JoystickAxis.Y:
  62699. case JoystickAxis.Z:
  62700. this._axisTargetedByLeftAndRight = axis;
  62701. break;
  62702. default:
  62703. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  62704. break;
  62705. }
  62706. };
  62707. // Define which axis you'd like to control for up & down
  62708. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  62709. switch (axis) {
  62710. case JoystickAxis.X:
  62711. case JoystickAxis.Y:
  62712. case JoystickAxis.Z:
  62713. this._axisTargetedByUpAndDown = axis;
  62714. break;
  62715. default:
  62716. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  62717. break;
  62718. }
  62719. };
  62720. VirtualJoystick.prototype._clearCanvas = function () {
  62721. if (this._leftJoystick) {
  62722. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  62723. }
  62724. else {
  62725. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  62726. }
  62727. };
  62728. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  62729. var _this = this;
  62730. if (this.pressed) {
  62731. this._touches.forEach(function (key, touch) {
  62732. if (touch.pointerId === _this._joystickPointerID) {
  62733. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  62734. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  62735. VirtualJoystick.vjCanvasContext.beginPath();
  62736. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  62737. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62738. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  62739. VirtualJoystick.vjCanvasContext.stroke();
  62740. VirtualJoystick.vjCanvasContext.closePath();
  62741. VirtualJoystick.vjCanvasContext.beginPath();
  62742. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62743. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  62744. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  62745. VirtualJoystick.vjCanvasContext.stroke();
  62746. VirtualJoystick.vjCanvasContext.closePath();
  62747. VirtualJoystick.vjCanvasContext.beginPath();
  62748. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  62749. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  62750. VirtualJoystick.vjCanvasContext.stroke();
  62751. VirtualJoystick.vjCanvasContext.closePath();
  62752. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  62753. }
  62754. else {
  62755. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  62756. VirtualJoystick.vjCanvasContext.beginPath();
  62757. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  62758. VirtualJoystick.vjCanvasContext.beginPath();
  62759. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  62760. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  62761. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  62762. VirtualJoystick.vjCanvasContext.stroke();
  62763. VirtualJoystick.vjCanvasContext.closePath();
  62764. touch.prevX = touch.x;
  62765. touch.prevY = touch.y;
  62766. }
  62767. ;
  62768. });
  62769. }
  62770. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  62771. };
  62772. VirtualJoystick.prototype.releaseCanvas = function () {
  62773. if (VirtualJoystick.vjCanvas) {
  62774. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  62775. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  62776. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  62777. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  62778. window.removeEventListener("resize", this._onResize);
  62779. document.body.removeChild(VirtualJoystick.vjCanvas);
  62780. VirtualJoystick.vjCanvas = null;
  62781. }
  62782. };
  62783. return VirtualJoystick;
  62784. }());
  62785. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  62786. VirtualJoystick._globalJoystickIndex = 0;
  62787. BABYLON.VirtualJoystick = VirtualJoystick;
  62788. })(BABYLON || (BABYLON = {}));
  62789. //# sourceMappingURL=babylon.virtualJoystick.js.map
  62790. var BABYLON;
  62791. (function (BABYLON) {
  62792. // We're mainly based on the logic defined into the FreeCamera code
  62793. var VirtualJoysticksCamera = (function (_super) {
  62794. __extends(VirtualJoysticksCamera, _super);
  62795. function VirtualJoysticksCamera(name, position, scene) {
  62796. var _this = _super.call(this, name, position, scene) || this;
  62797. _this.inputs.addVirtualJoystick();
  62798. return _this;
  62799. }
  62800. VirtualJoysticksCamera.prototype.getClassName = function () {
  62801. return "VirtualJoysticksCamera";
  62802. };
  62803. return VirtualJoysticksCamera;
  62804. }(BABYLON.FreeCamera));
  62805. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  62806. })(BABYLON || (BABYLON = {}));
  62807. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  62808. var BABYLON;
  62809. (function (BABYLON) {
  62810. var FreeCameraVirtualJoystickInput = (function () {
  62811. function FreeCameraVirtualJoystickInput() {
  62812. }
  62813. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  62814. return this._leftjoystick;
  62815. };
  62816. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  62817. return this._rightjoystick;
  62818. };
  62819. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  62820. if (this._leftjoystick) {
  62821. var camera = this.camera;
  62822. var speed = camera._computeLocalCameraSpeed() * 50;
  62823. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  62824. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  62825. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  62826. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  62827. if (!this._leftjoystick.pressed) {
  62828. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  62829. }
  62830. if (!this._rightjoystick.pressed) {
  62831. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  62832. }
  62833. }
  62834. };
  62835. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  62836. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  62837. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  62838. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  62839. this._leftjoystick.setJoystickSensibility(0.15);
  62840. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  62841. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  62842. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  62843. this._rightjoystick.reverseUpDown = true;
  62844. this._rightjoystick.setJoystickSensibility(0.05);
  62845. this._rightjoystick.setJoystickColor("yellow");
  62846. };
  62847. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  62848. this._leftjoystick.releaseCanvas();
  62849. this._rightjoystick.releaseCanvas();
  62850. };
  62851. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  62852. return "FreeCameraVirtualJoystickInput";
  62853. };
  62854. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  62855. return "virtualJoystick";
  62856. };
  62857. return FreeCameraVirtualJoystickInput;
  62858. }());
  62859. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  62860. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  62861. })(BABYLON || (BABYLON = {}));
  62862. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  62863. var BABYLON;
  62864. (function (BABYLON) {
  62865. var SimplificationSettings = (function () {
  62866. function SimplificationSettings(quality, distance, optimizeMesh) {
  62867. this.quality = quality;
  62868. this.distance = distance;
  62869. this.optimizeMesh = optimizeMesh;
  62870. }
  62871. return SimplificationSettings;
  62872. }());
  62873. BABYLON.SimplificationSettings = SimplificationSettings;
  62874. var SimplificationQueue = (function () {
  62875. function SimplificationQueue() {
  62876. this.running = false;
  62877. this._simplificationArray = [];
  62878. }
  62879. SimplificationQueue.prototype.addTask = function (task) {
  62880. this._simplificationArray.push(task);
  62881. };
  62882. SimplificationQueue.prototype.executeNext = function () {
  62883. var task = this._simplificationArray.pop();
  62884. if (task) {
  62885. this.running = true;
  62886. this.runSimplification(task);
  62887. }
  62888. else {
  62889. this.running = false;
  62890. }
  62891. };
  62892. SimplificationQueue.prototype.runSimplification = function (task) {
  62893. var _this = this;
  62894. if (task.parallelProcessing) {
  62895. //parallel simplifier
  62896. task.settings.forEach(function (setting) {
  62897. var simplifier = _this.getSimplifier(task);
  62898. simplifier.simplify(setting, function (newMesh) {
  62899. task.mesh.addLODLevel(setting.distance, newMesh);
  62900. newMesh.isVisible = true;
  62901. //check if it is the last
  62902. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  62903. //all done, run the success callback.
  62904. task.successCallback();
  62905. }
  62906. _this.executeNext();
  62907. });
  62908. });
  62909. }
  62910. else {
  62911. //single simplifier.
  62912. var simplifier = this.getSimplifier(task);
  62913. var runDecimation = function (setting, callback) {
  62914. simplifier.simplify(setting, function (newMesh) {
  62915. task.mesh.addLODLevel(setting.distance, newMesh);
  62916. newMesh.isVisible = true;
  62917. //run the next quality level
  62918. callback();
  62919. });
  62920. };
  62921. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  62922. runDecimation(task.settings[loop.index], function () {
  62923. loop.executeNext();
  62924. });
  62925. }, function () {
  62926. //execution ended, run the success callback.
  62927. if (task.successCallback) {
  62928. task.successCallback();
  62929. }
  62930. _this.executeNext();
  62931. });
  62932. }
  62933. };
  62934. SimplificationQueue.prototype.getSimplifier = function (task) {
  62935. switch (task.simplificationType) {
  62936. case SimplificationType.QUADRATIC:
  62937. default:
  62938. return new QuadraticErrorSimplification(task.mesh);
  62939. }
  62940. };
  62941. return SimplificationQueue;
  62942. }());
  62943. BABYLON.SimplificationQueue = SimplificationQueue;
  62944. /**
  62945. * The implemented types of simplification.
  62946. * At the moment only Quadratic Error Decimation is implemented.
  62947. */
  62948. var SimplificationType;
  62949. (function (SimplificationType) {
  62950. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  62951. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  62952. var DecimationTriangle = (function () {
  62953. function DecimationTriangle(vertices) {
  62954. this.vertices = vertices;
  62955. this.error = new Array(4);
  62956. this.deleted = false;
  62957. this.isDirty = false;
  62958. this.deletePending = false;
  62959. this.borderFactor = 0;
  62960. }
  62961. return DecimationTriangle;
  62962. }());
  62963. BABYLON.DecimationTriangle = DecimationTriangle;
  62964. var DecimationVertex = (function () {
  62965. function DecimationVertex(position, id) {
  62966. this.position = position;
  62967. this.id = id;
  62968. this.isBorder = true;
  62969. this.q = new QuadraticMatrix();
  62970. this.triangleCount = 0;
  62971. this.triangleStart = 0;
  62972. this.originalOffsets = [];
  62973. }
  62974. DecimationVertex.prototype.updatePosition = function (newPosition) {
  62975. this.position.copyFrom(newPosition);
  62976. };
  62977. return DecimationVertex;
  62978. }());
  62979. BABYLON.DecimationVertex = DecimationVertex;
  62980. var QuadraticMatrix = (function () {
  62981. function QuadraticMatrix(data) {
  62982. this.data = new Array(10);
  62983. for (var i = 0; i < 10; ++i) {
  62984. if (data && data[i]) {
  62985. this.data[i] = data[i];
  62986. }
  62987. else {
  62988. this.data[i] = 0;
  62989. }
  62990. }
  62991. }
  62992. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  62993. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  62994. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  62995. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  62996. return det;
  62997. };
  62998. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  62999. for (var i = 0; i < 10; ++i) {
  63000. this.data[i] += matrix.data[i];
  63001. }
  63002. };
  63003. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  63004. for (var i = 0; i < 10; ++i) {
  63005. this.data[i] += data[i];
  63006. }
  63007. };
  63008. QuadraticMatrix.prototype.add = function (matrix) {
  63009. var m = new QuadraticMatrix();
  63010. for (var i = 0; i < 10; ++i) {
  63011. m.data[i] = this.data[i] + matrix.data[i];
  63012. }
  63013. return m;
  63014. };
  63015. QuadraticMatrix.FromData = function (a, b, c, d) {
  63016. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  63017. };
  63018. //returning an array to avoid garbage collection
  63019. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  63020. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  63021. };
  63022. return QuadraticMatrix;
  63023. }());
  63024. BABYLON.QuadraticMatrix = QuadraticMatrix;
  63025. var Reference = (function () {
  63026. function Reference(vertexId, triangleId) {
  63027. this.vertexId = vertexId;
  63028. this.triangleId = triangleId;
  63029. }
  63030. return Reference;
  63031. }());
  63032. BABYLON.Reference = Reference;
  63033. /**
  63034. * An implementation of the Quadratic Error simplification algorithm.
  63035. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  63036. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  63037. * @author RaananW
  63038. */
  63039. var QuadraticErrorSimplification = (function () {
  63040. function QuadraticErrorSimplification(_mesh) {
  63041. this._mesh = _mesh;
  63042. this.initialized = false;
  63043. this.syncIterations = 5000;
  63044. this.aggressiveness = 7;
  63045. this.decimationIterations = 100;
  63046. this.boundingBoxEpsilon = BABYLON.Epsilon;
  63047. }
  63048. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  63049. var _this = this;
  63050. this.initDecimatedMesh();
  63051. //iterating through the submeshes array, one after the other.
  63052. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  63053. _this.initWithMesh(loop.index, function () {
  63054. _this.runDecimation(settings, loop.index, function () {
  63055. loop.executeNext();
  63056. });
  63057. }, settings.optimizeMesh);
  63058. }, function () {
  63059. setTimeout(function () {
  63060. successCallback(_this._reconstructedMesh);
  63061. }, 0);
  63062. });
  63063. };
  63064. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  63065. var _this = this;
  63066. var gCount = 0;
  63067. triangle.vertices.forEach(function (vertex) {
  63068. var count = 0;
  63069. var vPos = vertex.position;
  63070. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  63071. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  63072. ++count;
  63073. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  63074. ++count;
  63075. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  63076. ++count;
  63077. if (count > 1) {
  63078. ++gCount;
  63079. }
  63080. ;
  63081. });
  63082. if (gCount > 1) {
  63083. console.log(triangle, gCount);
  63084. }
  63085. return gCount > 1;
  63086. };
  63087. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  63088. var _this = this;
  63089. var targetCount = ~~(this.triangles.length * settings.quality);
  63090. var deletedTriangles = 0;
  63091. var triangleCount = this.triangles.length;
  63092. var iterationFunction = function (iteration, callback) {
  63093. setTimeout(function () {
  63094. if (iteration % 5 === 0) {
  63095. _this.updateMesh(iteration === 0);
  63096. }
  63097. for (var i = 0; i < _this.triangles.length; ++i) {
  63098. _this.triangles[i].isDirty = false;
  63099. }
  63100. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  63101. var trianglesIterator = function (i) {
  63102. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  63103. var t = _this.triangles[tIdx];
  63104. if (!t)
  63105. return;
  63106. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  63107. return;
  63108. }
  63109. for (var j = 0; j < 3; ++j) {
  63110. if (t.error[j] < threshold) {
  63111. var deleted0 = [];
  63112. var deleted1 = [];
  63113. var v0 = t.vertices[j];
  63114. var v1 = t.vertices[(j + 1) % 3];
  63115. if (v0.isBorder || v1.isBorder)
  63116. continue;
  63117. var p = BABYLON.Vector3.Zero();
  63118. var n = BABYLON.Vector3.Zero();
  63119. var uv = BABYLON.Vector2.Zero();
  63120. var color = new BABYLON.Color4(0, 0, 0, 1);
  63121. _this.calculateError(v0, v1, p, n, uv, color);
  63122. var delTr = [];
  63123. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  63124. continue;
  63125. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  63126. continue;
  63127. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  63128. continue;
  63129. var uniqueArray = [];
  63130. delTr.forEach(function (deletedT) {
  63131. if (uniqueArray.indexOf(deletedT) === -1) {
  63132. deletedT.deletePending = true;
  63133. uniqueArray.push(deletedT);
  63134. }
  63135. });
  63136. if (uniqueArray.length % 2 !== 0) {
  63137. continue;
  63138. }
  63139. v0.q = v1.q.add(v0.q);
  63140. v0.updatePosition(p);
  63141. var tStart = _this.references.length;
  63142. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  63143. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  63144. var tCount = _this.references.length - tStart;
  63145. if (tCount <= v0.triangleCount) {
  63146. if (tCount) {
  63147. for (var c = 0; c < tCount; c++) {
  63148. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  63149. }
  63150. }
  63151. }
  63152. else {
  63153. v0.triangleStart = tStart;
  63154. }
  63155. v0.triangleCount = tCount;
  63156. break;
  63157. }
  63158. }
  63159. };
  63160. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  63161. }, 0);
  63162. };
  63163. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  63164. if (triangleCount - deletedTriangles <= targetCount)
  63165. loop.breakLoop();
  63166. else {
  63167. iterationFunction(loop.index, function () {
  63168. loop.executeNext();
  63169. });
  63170. }
  63171. }, function () {
  63172. setTimeout(function () {
  63173. //reconstruct this part of the mesh
  63174. _this.reconstructMesh(submeshIndex);
  63175. successCallback();
  63176. }, 0);
  63177. });
  63178. };
  63179. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  63180. var _this = this;
  63181. this.vertices = [];
  63182. this.triangles = [];
  63183. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63184. var indices = this._mesh.getIndices();
  63185. var submesh = this._mesh.subMeshes[submeshIndex];
  63186. var findInVertices = function (positionToSearch) {
  63187. if (optimizeMesh) {
  63188. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  63189. if (_this.vertices[ii].position.equals(positionToSearch)) {
  63190. return _this.vertices[ii];
  63191. }
  63192. }
  63193. }
  63194. return null;
  63195. };
  63196. var vertexReferences = [];
  63197. var vertexInit = function (i) {
  63198. var offset = i + submesh.verticesStart;
  63199. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  63200. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  63201. vertex.originalOffsets.push(offset);
  63202. if (vertex.id === _this.vertices.length) {
  63203. _this.vertices.push(vertex);
  63204. }
  63205. vertexReferences.push(vertex.id);
  63206. };
  63207. //var totalVertices = mesh.getTotalVertices();
  63208. var totalVertices = submesh.verticesCount;
  63209. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  63210. var indicesInit = function (i) {
  63211. var offset = (submesh.indexStart / 3) + i;
  63212. var pos = (offset * 3);
  63213. var i0 = indices[pos + 0];
  63214. var i1 = indices[pos + 1];
  63215. var i2 = indices[pos + 2];
  63216. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  63217. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  63218. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  63219. var triangle = new DecimationTriangle([v0, v1, v2]);
  63220. triangle.originalOffset = pos;
  63221. _this.triangles.push(triangle);
  63222. };
  63223. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  63224. _this.init(callback);
  63225. });
  63226. });
  63227. };
  63228. QuadraticErrorSimplification.prototype.init = function (callback) {
  63229. var _this = this;
  63230. var triangleInit1 = function (i) {
  63231. var t = _this.triangles[i];
  63232. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  63233. for (var j = 0; j < 3; j++) {
  63234. 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))));
  63235. }
  63236. };
  63237. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  63238. var triangleInit2 = function (i) {
  63239. var t = _this.triangles[i];
  63240. for (var j = 0; j < 3; ++j) {
  63241. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  63242. }
  63243. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  63244. };
  63245. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  63246. _this.initialized = true;
  63247. callback();
  63248. });
  63249. });
  63250. };
  63251. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  63252. var newTriangles = [];
  63253. var i;
  63254. for (i = 0; i < this.vertices.length; ++i) {
  63255. this.vertices[i].triangleCount = 0;
  63256. }
  63257. var t;
  63258. var j;
  63259. for (i = 0; i < this.triangles.length; ++i) {
  63260. if (!this.triangles[i].deleted) {
  63261. t = this.triangles[i];
  63262. for (j = 0; j < 3; ++j) {
  63263. t.vertices[j].triangleCount = 1;
  63264. }
  63265. newTriangles.push(t);
  63266. }
  63267. }
  63268. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  63269. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  63270. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  63271. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  63272. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63273. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63274. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63275. var vertexCount = 0;
  63276. for (i = 0; i < this.vertices.length; ++i) {
  63277. var vertex = this.vertices[i];
  63278. vertex.id = vertexCount;
  63279. if (vertex.triangleCount) {
  63280. vertex.originalOffsets.forEach(function (originalOffset) {
  63281. newPositionData.push(vertex.position.x);
  63282. newPositionData.push(vertex.position.y);
  63283. newPositionData.push(vertex.position.z);
  63284. newNormalData.push(normalData[originalOffset * 3]);
  63285. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  63286. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  63287. if (uvs && uvs.length) {
  63288. newUVsData.push(uvs[(originalOffset * 2)]);
  63289. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  63290. }
  63291. else if (colorsData && colorsData.length) {
  63292. newColorsData.push(colorsData[(originalOffset * 4)]);
  63293. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  63294. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  63295. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  63296. }
  63297. ++vertexCount;
  63298. });
  63299. }
  63300. }
  63301. var startingIndex = this._reconstructedMesh.getTotalIndices();
  63302. var startingVertex = this._reconstructedMesh.getTotalVertices();
  63303. var submeshesArray = this._reconstructedMesh.subMeshes;
  63304. this._reconstructedMesh.subMeshes = [];
  63305. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  63306. var originalIndices = this._mesh.getIndices();
  63307. for (i = 0; i < newTriangles.length; ++i) {
  63308. t = newTriangles[i]; //now get the new referencing point for each vertex
  63309. [0, 1, 2].forEach(function (idx) {
  63310. var id = originalIndices[t.originalOffset + idx];
  63311. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  63312. if (offset < 0)
  63313. offset = 0;
  63314. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  63315. });
  63316. }
  63317. //overwriting the old vertex buffers and indices.
  63318. this._reconstructedMesh.setIndices(newIndicesArray);
  63319. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  63320. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  63321. if (newUVsData.length > 0)
  63322. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  63323. if (newColorsData.length > 0)
  63324. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  63325. //create submesh
  63326. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  63327. if (submeshIndex > 0) {
  63328. this._reconstructedMesh.subMeshes = [];
  63329. submeshesArray.forEach(function (submesh) {
  63330. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  63331. });
  63332. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  63333. }
  63334. };
  63335. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  63336. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  63337. this._reconstructedMesh.material = this._mesh.material;
  63338. this._reconstructedMesh.parent = this._mesh.parent;
  63339. this._reconstructedMesh.isVisible = false;
  63340. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  63341. };
  63342. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  63343. for (var i = 0; i < vertex1.triangleCount; ++i) {
  63344. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  63345. if (t.deleted)
  63346. continue;
  63347. var s = this.references[vertex1.triangleStart + i].vertexId;
  63348. var v1 = t.vertices[(s + 1) % 3];
  63349. var v2 = t.vertices[(s + 2) % 3];
  63350. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  63351. deletedArray[i] = true;
  63352. delTr.push(t);
  63353. continue;
  63354. }
  63355. var d1 = v1.position.subtract(point);
  63356. d1 = d1.normalize();
  63357. var d2 = v2.position.subtract(point);
  63358. d2 = d2.normalize();
  63359. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  63360. return true;
  63361. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  63362. deletedArray[i] = false;
  63363. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  63364. return true;
  63365. }
  63366. return false;
  63367. };
  63368. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  63369. var newDeleted = deletedTriangles;
  63370. for (var i = 0; i < vertex.triangleCount; ++i) {
  63371. var ref = this.references[vertex.triangleStart + i];
  63372. var t = this.triangles[ref.triangleId];
  63373. if (t.deleted)
  63374. continue;
  63375. if (deletedArray[i] && t.deletePending) {
  63376. t.deleted = true;
  63377. newDeleted++;
  63378. continue;
  63379. }
  63380. t.vertices[ref.vertexId] = origVertex;
  63381. t.isDirty = true;
  63382. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  63383. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  63384. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  63385. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  63386. this.references.push(ref);
  63387. }
  63388. return newDeleted;
  63389. };
  63390. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  63391. for (var i = 0; i < this.vertices.length; ++i) {
  63392. var vCount = [];
  63393. var vId = [];
  63394. var v = this.vertices[i];
  63395. var j;
  63396. for (j = 0; j < v.triangleCount; ++j) {
  63397. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  63398. for (var ii = 0; ii < 3; ii++) {
  63399. var ofs = 0;
  63400. var vv = triangle.vertices[ii];
  63401. while (ofs < vCount.length) {
  63402. if (vId[ofs] === vv.id)
  63403. break;
  63404. ++ofs;
  63405. }
  63406. if (ofs === vCount.length) {
  63407. vCount.push(1);
  63408. vId.push(vv.id);
  63409. }
  63410. else {
  63411. vCount[ofs]++;
  63412. }
  63413. }
  63414. }
  63415. for (j = 0; j < vCount.length; ++j) {
  63416. if (vCount[j] === 1) {
  63417. this.vertices[vId[j]].isBorder = true;
  63418. }
  63419. else {
  63420. this.vertices[vId[j]].isBorder = false;
  63421. }
  63422. }
  63423. }
  63424. };
  63425. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  63426. if (identifyBorders === void 0) { identifyBorders = false; }
  63427. var i;
  63428. if (!identifyBorders) {
  63429. var newTrianglesVector = [];
  63430. for (i = 0; i < this.triangles.length; ++i) {
  63431. if (!this.triangles[i].deleted) {
  63432. newTrianglesVector.push(this.triangles[i]);
  63433. }
  63434. }
  63435. this.triangles = newTrianglesVector;
  63436. }
  63437. for (i = 0; i < this.vertices.length; ++i) {
  63438. this.vertices[i].triangleCount = 0;
  63439. this.vertices[i].triangleStart = 0;
  63440. }
  63441. var t;
  63442. var j;
  63443. var v;
  63444. for (i = 0; i < this.triangles.length; ++i) {
  63445. t = this.triangles[i];
  63446. for (j = 0; j < 3; ++j) {
  63447. v = t.vertices[j];
  63448. v.triangleCount++;
  63449. }
  63450. }
  63451. var tStart = 0;
  63452. for (i = 0; i < this.vertices.length; ++i) {
  63453. this.vertices[i].triangleStart = tStart;
  63454. tStart += this.vertices[i].triangleCount;
  63455. this.vertices[i].triangleCount = 0;
  63456. }
  63457. var newReferences = new Array(this.triangles.length * 3);
  63458. for (i = 0; i < this.triangles.length; ++i) {
  63459. t = this.triangles[i];
  63460. for (j = 0; j < 3; ++j) {
  63461. v = t.vertices[j];
  63462. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  63463. v.triangleCount++;
  63464. }
  63465. }
  63466. this.references = newReferences;
  63467. if (identifyBorders) {
  63468. this.identifyBorder();
  63469. }
  63470. };
  63471. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  63472. var x = point.x;
  63473. var y = point.y;
  63474. var z = point.z;
  63475. 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
  63476. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  63477. };
  63478. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  63479. var q = vertex1.q.add(vertex2.q);
  63480. var border = vertex1.isBorder && vertex2.isBorder;
  63481. var error = 0;
  63482. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  63483. if (qDet !== 0 && !border) {
  63484. if (!pointResult) {
  63485. pointResult = BABYLON.Vector3.Zero();
  63486. }
  63487. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  63488. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  63489. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  63490. error = this.vertexError(q, pointResult);
  63491. }
  63492. else {
  63493. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  63494. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  63495. var error1 = this.vertexError(q, vertex1.position);
  63496. var error2 = this.vertexError(q, vertex2.position);
  63497. var error3 = this.vertexError(q, p3);
  63498. error = Math.min(error1, error2, error3);
  63499. if (error === error1) {
  63500. if (pointResult) {
  63501. pointResult.copyFrom(vertex1.position);
  63502. }
  63503. }
  63504. else if (error === error2) {
  63505. if (pointResult) {
  63506. pointResult.copyFrom(vertex2.position);
  63507. }
  63508. }
  63509. else {
  63510. if (pointResult) {
  63511. pointResult.copyFrom(p3);
  63512. }
  63513. }
  63514. }
  63515. return error;
  63516. };
  63517. return QuadraticErrorSimplification;
  63518. }());
  63519. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  63520. })(BABYLON || (BABYLON = {}));
  63521. //# sourceMappingURL=babylon.meshSimplification.js.map
  63522. var BABYLON;
  63523. (function (BABYLON) {
  63524. var Internals;
  63525. (function (Internals) {
  63526. var MeshLODLevel = (function () {
  63527. function MeshLODLevel(distance, mesh) {
  63528. this.distance = distance;
  63529. this.mesh = mesh;
  63530. }
  63531. return MeshLODLevel;
  63532. }());
  63533. Internals.MeshLODLevel = MeshLODLevel;
  63534. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63535. })(BABYLON || (BABYLON = {}));
  63536. //# sourceMappingURL=babylon.meshLODLevel.js.map
  63537. var BABYLON;
  63538. (function (BABYLON) {
  63539. // Standard optimizations
  63540. var SceneOptimization = (function () {
  63541. function SceneOptimization(priority) {
  63542. if (priority === void 0) { priority = 0; }
  63543. this.priority = priority;
  63544. this.apply = function (scene) {
  63545. return true; // Return true if everything that can be done was applied
  63546. };
  63547. }
  63548. return SceneOptimization;
  63549. }());
  63550. BABYLON.SceneOptimization = SceneOptimization;
  63551. var TextureOptimization = (function (_super) {
  63552. __extends(TextureOptimization, _super);
  63553. function TextureOptimization(priority, maximumSize) {
  63554. if (priority === void 0) { priority = 0; }
  63555. if (maximumSize === void 0) { maximumSize = 1024; }
  63556. var _this = _super.call(this, priority) || this;
  63557. _this.priority = priority;
  63558. _this.maximumSize = maximumSize;
  63559. _this.apply = function (scene) {
  63560. var allDone = true;
  63561. for (var index = 0; index < scene.textures.length; index++) {
  63562. var texture = scene.textures[index];
  63563. if (!texture.canRescale) {
  63564. continue;
  63565. }
  63566. var currentSize = texture.getSize();
  63567. var maxDimension = Math.max(currentSize.width, currentSize.height);
  63568. if (maxDimension > _this.maximumSize) {
  63569. texture.scale(0.5);
  63570. allDone = false;
  63571. }
  63572. }
  63573. return allDone;
  63574. };
  63575. return _this;
  63576. }
  63577. return TextureOptimization;
  63578. }(SceneOptimization));
  63579. BABYLON.TextureOptimization = TextureOptimization;
  63580. var HardwareScalingOptimization = (function (_super) {
  63581. __extends(HardwareScalingOptimization, _super);
  63582. function HardwareScalingOptimization(priority, maximumScale) {
  63583. if (priority === void 0) { priority = 0; }
  63584. if (maximumScale === void 0) { maximumScale = 2; }
  63585. var _this = _super.call(this, priority) || this;
  63586. _this.priority = priority;
  63587. _this.maximumScale = maximumScale;
  63588. _this._currentScale = 1;
  63589. _this.apply = function (scene) {
  63590. _this._currentScale++;
  63591. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  63592. return _this._currentScale >= _this.maximumScale;
  63593. };
  63594. return _this;
  63595. }
  63596. return HardwareScalingOptimization;
  63597. }(SceneOptimization));
  63598. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  63599. var ShadowsOptimization = (function (_super) {
  63600. __extends(ShadowsOptimization, _super);
  63601. function ShadowsOptimization() {
  63602. var _this = _super !== null && _super.apply(this, arguments) || this;
  63603. _this.apply = function (scene) {
  63604. scene.shadowsEnabled = false;
  63605. return true;
  63606. };
  63607. return _this;
  63608. }
  63609. return ShadowsOptimization;
  63610. }(SceneOptimization));
  63611. BABYLON.ShadowsOptimization = ShadowsOptimization;
  63612. var PostProcessesOptimization = (function (_super) {
  63613. __extends(PostProcessesOptimization, _super);
  63614. function PostProcessesOptimization() {
  63615. var _this = _super !== null && _super.apply(this, arguments) || this;
  63616. _this.apply = function (scene) {
  63617. scene.postProcessesEnabled = false;
  63618. return true;
  63619. };
  63620. return _this;
  63621. }
  63622. return PostProcessesOptimization;
  63623. }(SceneOptimization));
  63624. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  63625. var LensFlaresOptimization = (function (_super) {
  63626. __extends(LensFlaresOptimization, _super);
  63627. function LensFlaresOptimization() {
  63628. var _this = _super !== null && _super.apply(this, arguments) || this;
  63629. _this.apply = function (scene) {
  63630. scene.lensFlaresEnabled = false;
  63631. return true;
  63632. };
  63633. return _this;
  63634. }
  63635. return LensFlaresOptimization;
  63636. }(SceneOptimization));
  63637. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  63638. var ParticlesOptimization = (function (_super) {
  63639. __extends(ParticlesOptimization, _super);
  63640. function ParticlesOptimization() {
  63641. var _this = _super !== null && _super.apply(this, arguments) || this;
  63642. _this.apply = function (scene) {
  63643. scene.particlesEnabled = false;
  63644. return true;
  63645. };
  63646. return _this;
  63647. }
  63648. return ParticlesOptimization;
  63649. }(SceneOptimization));
  63650. BABYLON.ParticlesOptimization = ParticlesOptimization;
  63651. var RenderTargetsOptimization = (function (_super) {
  63652. __extends(RenderTargetsOptimization, _super);
  63653. function RenderTargetsOptimization() {
  63654. var _this = _super !== null && _super.apply(this, arguments) || this;
  63655. _this.apply = function (scene) {
  63656. scene.renderTargetsEnabled = false;
  63657. return true;
  63658. };
  63659. return _this;
  63660. }
  63661. return RenderTargetsOptimization;
  63662. }(SceneOptimization));
  63663. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  63664. var MergeMeshesOptimization = (function (_super) {
  63665. __extends(MergeMeshesOptimization, _super);
  63666. function MergeMeshesOptimization() {
  63667. var _this = _super !== null && _super.apply(this, arguments) || this;
  63668. _this._canBeMerged = function (abstractMesh) {
  63669. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  63670. return false;
  63671. }
  63672. var mesh = abstractMesh;
  63673. if (!mesh.isVisible || !mesh.isEnabled()) {
  63674. return false;
  63675. }
  63676. if (mesh.instances.length > 0) {
  63677. return false;
  63678. }
  63679. if (mesh.skeleton || mesh.hasLODLevels) {
  63680. return false;
  63681. }
  63682. if (mesh.parent) {
  63683. return false;
  63684. }
  63685. return true;
  63686. };
  63687. _this.apply = function (scene, updateSelectionTree) {
  63688. var globalPool = scene.meshes.slice(0);
  63689. var globalLength = globalPool.length;
  63690. for (var index = 0; index < globalLength; index++) {
  63691. var currentPool = new Array();
  63692. var current = globalPool[index];
  63693. // Checks
  63694. if (!_this._canBeMerged(current)) {
  63695. continue;
  63696. }
  63697. currentPool.push(current);
  63698. // Find compatible meshes
  63699. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  63700. var otherMesh = globalPool[subIndex];
  63701. if (!_this._canBeMerged(otherMesh)) {
  63702. continue;
  63703. }
  63704. if (otherMesh.material !== current.material) {
  63705. continue;
  63706. }
  63707. if (otherMesh.checkCollisions !== current.checkCollisions) {
  63708. continue;
  63709. }
  63710. currentPool.push(otherMesh);
  63711. globalLength--;
  63712. globalPool.splice(subIndex, 1);
  63713. subIndex--;
  63714. }
  63715. if (currentPool.length < 2) {
  63716. continue;
  63717. }
  63718. // Merge meshes
  63719. BABYLON.Mesh.MergeMeshes(currentPool);
  63720. }
  63721. if (updateSelectionTree != undefined) {
  63722. if (updateSelectionTree) {
  63723. scene.createOrUpdateSelectionOctree();
  63724. }
  63725. }
  63726. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  63727. scene.createOrUpdateSelectionOctree();
  63728. }
  63729. return true;
  63730. };
  63731. return _this;
  63732. }
  63733. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  63734. get: function () {
  63735. return MergeMeshesOptimization._UpdateSelectionTree;
  63736. },
  63737. set: function (value) {
  63738. MergeMeshesOptimization._UpdateSelectionTree = value;
  63739. },
  63740. enumerable: true,
  63741. configurable: true
  63742. });
  63743. return MergeMeshesOptimization;
  63744. }(SceneOptimization));
  63745. MergeMeshesOptimization._UpdateSelectionTree = false;
  63746. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  63747. // Options
  63748. var SceneOptimizerOptions = (function () {
  63749. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  63750. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  63751. if (trackerDuration === void 0) { trackerDuration = 2000; }
  63752. this.targetFrameRate = targetFrameRate;
  63753. this.trackerDuration = trackerDuration;
  63754. this.optimizations = new Array();
  63755. }
  63756. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  63757. var result = new SceneOptimizerOptions(targetFrameRate);
  63758. var priority = 0;
  63759. result.optimizations.push(new MergeMeshesOptimization(priority));
  63760. result.optimizations.push(new ShadowsOptimization(priority));
  63761. result.optimizations.push(new LensFlaresOptimization(priority));
  63762. // Next priority
  63763. priority++;
  63764. result.optimizations.push(new PostProcessesOptimization(priority));
  63765. result.optimizations.push(new ParticlesOptimization(priority));
  63766. // Next priority
  63767. priority++;
  63768. result.optimizations.push(new TextureOptimization(priority, 1024));
  63769. return result;
  63770. };
  63771. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  63772. var result = new SceneOptimizerOptions(targetFrameRate);
  63773. var priority = 0;
  63774. result.optimizations.push(new MergeMeshesOptimization(priority));
  63775. result.optimizations.push(new ShadowsOptimization(priority));
  63776. result.optimizations.push(new LensFlaresOptimization(priority));
  63777. // Next priority
  63778. priority++;
  63779. result.optimizations.push(new PostProcessesOptimization(priority));
  63780. result.optimizations.push(new ParticlesOptimization(priority));
  63781. // Next priority
  63782. priority++;
  63783. result.optimizations.push(new TextureOptimization(priority, 512));
  63784. // Next priority
  63785. priority++;
  63786. result.optimizations.push(new RenderTargetsOptimization(priority));
  63787. // Next priority
  63788. priority++;
  63789. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  63790. return result;
  63791. };
  63792. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  63793. var result = new SceneOptimizerOptions(targetFrameRate);
  63794. var priority = 0;
  63795. result.optimizations.push(new MergeMeshesOptimization(priority));
  63796. result.optimizations.push(new ShadowsOptimization(priority));
  63797. result.optimizations.push(new LensFlaresOptimization(priority));
  63798. // Next priority
  63799. priority++;
  63800. result.optimizations.push(new PostProcessesOptimization(priority));
  63801. result.optimizations.push(new ParticlesOptimization(priority));
  63802. // Next priority
  63803. priority++;
  63804. result.optimizations.push(new TextureOptimization(priority, 256));
  63805. // Next priority
  63806. priority++;
  63807. result.optimizations.push(new RenderTargetsOptimization(priority));
  63808. // Next priority
  63809. priority++;
  63810. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  63811. return result;
  63812. };
  63813. return SceneOptimizerOptions;
  63814. }());
  63815. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  63816. // Scene optimizer tool
  63817. var SceneOptimizer = (function () {
  63818. function SceneOptimizer() {
  63819. }
  63820. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  63821. // TODO: add an epsilon
  63822. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  63823. if (onSuccess) {
  63824. onSuccess();
  63825. }
  63826. return;
  63827. }
  63828. // Apply current level of optimizations
  63829. var allDone = true;
  63830. var noOptimizationApplied = true;
  63831. for (var index = 0; index < options.optimizations.length; index++) {
  63832. var optimization = options.optimizations[index];
  63833. if (optimization.priority === currentPriorityLevel) {
  63834. noOptimizationApplied = false;
  63835. allDone = allDone && optimization.apply(scene);
  63836. }
  63837. }
  63838. // If no optimization was applied, this is a failure :(
  63839. if (noOptimizationApplied) {
  63840. if (onFailure) {
  63841. onFailure();
  63842. }
  63843. return;
  63844. }
  63845. // If all optimizations were done, move to next level
  63846. if (allDone) {
  63847. currentPriorityLevel++;
  63848. }
  63849. // Let's the system running for a specific amount of time before checking FPS
  63850. scene.executeWhenReady(function () {
  63851. setTimeout(function () {
  63852. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  63853. }, options.trackerDuration);
  63854. });
  63855. };
  63856. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  63857. if (!options) {
  63858. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  63859. }
  63860. // Let's the system running for a specific amount of time before checking FPS
  63861. scene.executeWhenReady(function () {
  63862. setTimeout(function () {
  63863. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  63864. }, options.trackerDuration);
  63865. });
  63866. };
  63867. return SceneOptimizer;
  63868. }());
  63869. BABYLON.SceneOptimizer = SceneOptimizer;
  63870. })(BABYLON || (BABYLON = {}));
  63871. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  63872. var BABYLON;
  63873. (function (BABYLON) {
  63874. var OutlineRenderer = (function () {
  63875. function OutlineRenderer(scene) {
  63876. this.zOffset = 1;
  63877. this._scene = scene;
  63878. }
  63879. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  63880. var _this = this;
  63881. if (useOverlay === void 0) { useOverlay = false; }
  63882. var scene = this._scene;
  63883. var engine = this._scene.getEngine();
  63884. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  63885. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  63886. return;
  63887. }
  63888. var mesh = subMesh.getRenderingMesh();
  63889. var material = subMesh.getMaterial();
  63890. engine.enableEffect(this._effect);
  63891. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  63892. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  63893. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63894. // Bones
  63895. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63896. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63897. }
  63898. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  63899. // Alpha test
  63900. if (material && material.needAlphaTesting()) {
  63901. var alphaTexture = material.getAlphaTestTexture();
  63902. this._effect.setTexture("diffuseSampler", alphaTexture);
  63903. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63904. }
  63905. engine.setZOffset(-this.zOffset);
  63906. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  63907. engine.setZOffset(0);
  63908. };
  63909. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  63910. var defines = [];
  63911. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63912. var mesh = subMesh.getMesh();
  63913. var material = subMesh.getMaterial();
  63914. // Alpha test
  63915. if (material && material.needAlphaTesting()) {
  63916. defines.push("#define ALPHATEST");
  63917. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63918. attribs.push(BABYLON.VertexBuffer.UVKind);
  63919. defines.push("#define UV1");
  63920. }
  63921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63922. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63923. defines.push("#define UV2");
  63924. }
  63925. }
  63926. // Bones
  63927. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63928. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63929. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63930. if (mesh.numBoneInfluencers > 4) {
  63931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63933. }
  63934. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63935. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  63936. }
  63937. else {
  63938. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63939. }
  63940. // Instances
  63941. if (useInstances) {
  63942. defines.push("#define INSTANCES");
  63943. attribs.push("world0");
  63944. attribs.push("world1");
  63945. attribs.push("world2");
  63946. attribs.push("world3");
  63947. }
  63948. // Get correct effect
  63949. var join = defines.join("\n");
  63950. if (this._cachedDefines !== join) {
  63951. this._cachedDefines = join;
  63952. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  63953. }
  63954. return this._effect.isReady();
  63955. };
  63956. return OutlineRenderer;
  63957. }());
  63958. BABYLON.OutlineRenderer = OutlineRenderer;
  63959. })(BABYLON || (BABYLON = {}));
  63960. //# sourceMappingURL=babylon.outlineRenderer.js.map
  63961. var BABYLON;
  63962. (function (BABYLON) {
  63963. var FaceAdjacencies = (function () {
  63964. function FaceAdjacencies() {
  63965. this.edges = new Array();
  63966. this.edgesConnectedCount = 0;
  63967. }
  63968. return FaceAdjacencies;
  63969. }());
  63970. var EdgesRenderer = (function () {
  63971. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  63972. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  63973. if (epsilon === void 0) { epsilon = 0.95; }
  63974. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  63975. this.edgesWidthScalerForOrthographic = 1000.0;
  63976. this.edgesWidthScalerForPerspective = 50.0;
  63977. this._linesPositions = new Array();
  63978. this._linesNormals = new Array();
  63979. this._linesIndices = new Array();
  63980. this._buffers = {};
  63981. this._checkVerticesInsteadOfIndices = false;
  63982. this._source = source;
  63983. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  63984. this._epsilon = epsilon;
  63985. this._prepareRessources();
  63986. this._generateEdgesLines();
  63987. }
  63988. EdgesRenderer.prototype._prepareRessources = function () {
  63989. if (this._lineShader) {
  63990. return;
  63991. }
  63992. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  63993. attributes: ["position", "normal"],
  63994. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  63995. });
  63996. this._lineShader.disableDepthWrite = true;
  63997. this._lineShader.backFaceCulling = false;
  63998. };
  63999. EdgesRenderer.prototype.dispose = function () {
  64000. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  64001. if (buffer) {
  64002. buffer.dispose();
  64003. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  64004. }
  64005. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  64006. if (buffer) {
  64007. buffer.dispose();
  64008. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  64009. }
  64010. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  64011. this._lineShader.dispose();
  64012. };
  64013. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  64014. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  64015. return 0;
  64016. }
  64017. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  64018. return 1;
  64019. }
  64020. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  64021. return 2;
  64022. }
  64023. return -1;
  64024. };
  64025. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  64026. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  64027. return 0;
  64028. }
  64029. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  64030. return 1;
  64031. }
  64032. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  64033. return 2;
  64034. }
  64035. return -1;
  64036. };
  64037. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  64038. var needToCreateLine;
  64039. if (edge === undefined) {
  64040. needToCreateLine = true;
  64041. }
  64042. else {
  64043. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  64044. needToCreateLine = dotProduct < this._epsilon;
  64045. }
  64046. if (needToCreateLine) {
  64047. var offset = this._linesPositions.length / 3;
  64048. var normal = p0.subtract(p1);
  64049. normal.normalize();
  64050. // Positions
  64051. this._linesPositions.push(p0.x);
  64052. this._linesPositions.push(p0.y);
  64053. this._linesPositions.push(p0.z);
  64054. this._linesPositions.push(p0.x);
  64055. this._linesPositions.push(p0.y);
  64056. this._linesPositions.push(p0.z);
  64057. this._linesPositions.push(p1.x);
  64058. this._linesPositions.push(p1.y);
  64059. this._linesPositions.push(p1.z);
  64060. this._linesPositions.push(p1.x);
  64061. this._linesPositions.push(p1.y);
  64062. this._linesPositions.push(p1.z);
  64063. // Normals
  64064. this._linesNormals.push(p1.x);
  64065. this._linesNormals.push(p1.y);
  64066. this._linesNormals.push(p1.z);
  64067. this._linesNormals.push(-1);
  64068. this._linesNormals.push(p1.x);
  64069. this._linesNormals.push(p1.y);
  64070. this._linesNormals.push(p1.z);
  64071. this._linesNormals.push(1);
  64072. this._linesNormals.push(p0.x);
  64073. this._linesNormals.push(p0.y);
  64074. this._linesNormals.push(p0.z);
  64075. this._linesNormals.push(-1);
  64076. this._linesNormals.push(p0.x);
  64077. this._linesNormals.push(p0.y);
  64078. this._linesNormals.push(p0.z);
  64079. this._linesNormals.push(1);
  64080. // Indices
  64081. this._linesIndices.push(offset);
  64082. this._linesIndices.push(offset + 1);
  64083. this._linesIndices.push(offset + 2);
  64084. this._linesIndices.push(offset);
  64085. this._linesIndices.push(offset + 2);
  64086. this._linesIndices.push(offset + 3);
  64087. }
  64088. };
  64089. EdgesRenderer.prototype._generateEdgesLines = function () {
  64090. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64091. var indices = this._source.getIndices();
  64092. // First let's find adjacencies
  64093. var adjacencies = new Array();
  64094. var faceNormals = new Array();
  64095. var index;
  64096. var faceAdjacencies;
  64097. // Prepare faces
  64098. for (index = 0; index < indices.length; index += 3) {
  64099. faceAdjacencies = new FaceAdjacencies();
  64100. var p0Index = indices[index];
  64101. var p1Index = indices[index + 1];
  64102. var p2Index = indices[index + 2];
  64103. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  64104. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  64105. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  64106. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  64107. faceNormal.normalize();
  64108. faceNormals.push(faceNormal);
  64109. adjacencies.push(faceAdjacencies);
  64110. }
  64111. // Scan
  64112. for (index = 0; index < adjacencies.length; index++) {
  64113. faceAdjacencies = adjacencies[index];
  64114. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  64115. var otherFaceAdjacencies = adjacencies[otherIndex];
  64116. if (faceAdjacencies.edgesConnectedCount === 3) {
  64117. break;
  64118. }
  64119. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  64120. continue;
  64121. }
  64122. var otherP0 = indices[otherIndex * 3];
  64123. var otherP1 = indices[otherIndex * 3 + 1];
  64124. var otherP2 = indices[otherIndex * 3 + 2];
  64125. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  64126. var otherEdgeIndex;
  64127. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  64128. continue;
  64129. }
  64130. switch (edgeIndex) {
  64131. case 0:
  64132. if (this._checkVerticesInsteadOfIndices) {
  64133. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  64134. }
  64135. else {
  64136. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  64137. }
  64138. break;
  64139. case 1:
  64140. if (this._checkVerticesInsteadOfIndices) {
  64141. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  64142. }
  64143. else {
  64144. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  64145. }
  64146. break;
  64147. case 2:
  64148. if (this._checkVerticesInsteadOfIndices) {
  64149. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  64150. }
  64151. else {
  64152. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  64153. }
  64154. break;
  64155. }
  64156. if (otherEdgeIndex === -1) {
  64157. continue;
  64158. }
  64159. faceAdjacencies.edges[edgeIndex] = otherIndex;
  64160. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  64161. faceAdjacencies.edgesConnectedCount++;
  64162. otherFaceAdjacencies.edgesConnectedCount++;
  64163. if (faceAdjacencies.edgesConnectedCount === 3) {
  64164. break;
  64165. }
  64166. }
  64167. }
  64168. }
  64169. // Create lines
  64170. for (index = 0; index < adjacencies.length; index++) {
  64171. // 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
  64172. var current = adjacencies[index];
  64173. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  64174. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  64175. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  64176. }
  64177. // Merge into a single mesh
  64178. var engine = this._source.getScene().getEngine();
  64179. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  64180. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  64181. this._ib = engine.createIndexBuffer(this._linesIndices);
  64182. this._indicesCount = this._linesIndices.length;
  64183. };
  64184. EdgesRenderer.prototype.render = function () {
  64185. if (!this._lineShader.isReady()) {
  64186. return;
  64187. }
  64188. var scene = this._source.getScene();
  64189. var engine = scene.getEngine();
  64190. this._lineShader._preBind();
  64191. // VBOs
  64192. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  64193. scene.resetCachedMaterial();
  64194. this._lineShader.setColor4("color", this._source.edgesColor);
  64195. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  64196. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  64197. }
  64198. else {
  64199. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  64200. }
  64201. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  64202. this._lineShader.bind(this._source.getWorldMatrix());
  64203. // Draw order
  64204. engine.draw(true, 0, this._indicesCount);
  64205. this._lineShader.unbind();
  64206. engine.setDepthWrite(true);
  64207. };
  64208. return EdgesRenderer;
  64209. }());
  64210. BABYLON.EdgesRenderer = EdgesRenderer;
  64211. })(BABYLON || (BABYLON = {}));
  64212. //# sourceMappingURL=babylon.edgesRenderer.js.map
  64213. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  64214. /// <reference path="..\Math\babylon.math.ts" />
  64215. var BABYLON;
  64216. (function (BABYLON) {
  64217. /**
  64218. * Special Glow Blur post process only blurring the alpha channel
  64219. * It enforces keeping the most luminous color in the color channel.
  64220. */
  64221. var GlowBlurPostProcess = (function (_super) {
  64222. __extends(GlowBlurPostProcess, _super);
  64223. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  64224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64225. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  64226. _this.direction = direction;
  64227. _this.kernel = kernel;
  64228. _this.onApplyObservable.add(function (effect) {
  64229. effect.setFloat2("screenSize", _this.width, _this.height);
  64230. effect.setVector2("direction", _this.direction);
  64231. effect.setFloat("blurWidth", _this.kernel);
  64232. });
  64233. return _this;
  64234. }
  64235. return GlowBlurPostProcess;
  64236. }(BABYLON.PostProcess));
  64237. /**
  64238. * The highlight layer Helps adding a glow effect around a mesh.
  64239. *
  64240. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  64241. * glowy meshes to your scene.
  64242. *
  64243. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  64244. */
  64245. var HighlightLayer = (function () {
  64246. /**
  64247. * Instantiates a new highlight Layer and references it to the scene..
  64248. * @param name The name of the layer
  64249. * @param scene The scene to use the layer in
  64250. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  64251. */
  64252. function HighlightLayer(name, scene, options) {
  64253. this.name = name;
  64254. this._vertexBuffers = {};
  64255. this._mainTextureDesiredSize = { width: 0, height: 0 };
  64256. this._meshes = {};
  64257. this._maxSize = 0;
  64258. this._shouldRender = false;
  64259. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  64260. this._excludedMeshes = {};
  64261. /**
  64262. * Specifies whether or not the inner glow is ACTIVE in the layer.
  64263. */
  64264. this.innerGlow = true;
  64265. /**
  64266. * Specifies whether or not the outer glow is ACTIVE in the layer.
  64267. */
  64268. this.outerGlow = true;
  64269. /**
  64270. * Specifies wether the highlight layer is enabled or not.
  64271. */
  64272. this.isEnabled = true;
  64273. /**
  64274. * An event triggered when the highlight layer has been disposed.
  64275. * @type {BABYLON.Observable}
  64276. */
  64277. this.onDisposeObservable = new BABYLON.Observable();
  64278. /**
  64279. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  64280. * @type {BABYLON.Observable}
  64281. */
  64282. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  64283. /**
  64284. * An event triggered when the highlight layer is being blurred.
  64285. * @type {BABYLON.Observable}
  64286. */
  64287. this.onBeforeBlurObservable = new BABYLON.Observable();
  64288. /**
  64289. * An event triggered when the highlight layer has been blurred.
  64290. * @type {BABYLON.Observable}
  64291. */
  64292. this.onAfterBlurObservable = new BABYLON.Observable();
  64293. /**
  64294. * An event triggered when the glowing blurred texture is being merged in the scene.
  64295. * @type {BABYLON.Observable}
  64296. */
  64297. this.onBeforeComposeObservable = new BABYLON.Observable();
  64298. /**
  64299. * An event triggered when the glowing blurred texture has been merged in the scene.
  64300. * @type {BABYLON.Observable}
  64301. */
  64302. this.onAfterComposeObservable = new BABYLON.Observable();
  64303. /**
  64304. * An event triggered when the highlight layer changes its size.
  64305. * @type {BABYLON.Observable}
  64306. */
  64307. this.onSizeChangedObservable = new BABYLON.Observable();
  64308. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64309. var engine = scene.getEngine();
  64310. this._engine = engine;
  64311. this._maxSize = this._engine.getCaps().maxTextureSize;
  64312. this._scene.highlightLayers.push(this);
  64313. // Warn on stencil.
  64314. if (!this._engine.isStencilEnable) {
  64315. 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 }");
  64316. }
  64317. // Adapt options
  64318. this._options = options || {
  64319. mainTextureRatio: 0.25,
  64320. blurTextureSizeRatio: 0.5,
  64321. blurHorizontalSize: 1,
  64322. blurVerticalSize: 1,
  64323. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  64324. };
  64325. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  64326. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  64327. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  64328. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  64329. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  64330. // VBO
  64331. var vertices = [];
  64332. vertices.push(1, 1);
  64333. vertices.push(-1, 1);
  64334. vertices.push(-1, -1);
  64335. vertices.push(1, -1);
  64336. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64337. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  64338. // Indices
  64339. var indices = [];
  64340. indices.push(0);
  64341. indices.push(1);
  64342. indices.push(2);
  64343. indices.push(0);
  64344. indices.push(2);
  64345. indices.push(3);
  64346. this._indexBuffer = engine.createIndexBuffer(indices);
  64347. // Effect
  64348. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  64349. // Render target
  64350. this.setMainTextureSize();
  64351. // Create Textures and post processes
  64352. this.createTextureAndPostProcesses();
  64353. }
  64354. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  64355. /**
  64356. * Gets the horizontal size of the blur.
  64357. */
  64358. get: function () {
  64359. return this._horizontalBlurPostprocess.kernel;
  64360. },
  64361. /**
  64362. * Specifies the horizontal size of the blur.
  64363. */
  64364. set: function (value) {
  64365. this._horizontalBlurPostprocess.kernel = value;
  64366. },
  64367. enumerable: true,
  64368. configurable: true
  64369. });
  64370. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  64371. /**
  64372. * Gets the vertical size of the blur.
  64373. */
  64374. get: function () {
  64375. return this._verticalBlurPostprocess.kernel;
  64376. },
  64377. /**
  64378. * Specifies the vertical size of the blur.
  64379. */
  64380. set: function (value) {
  64381. this._verticalBlurPostprocess.kernel = value;
  64382. },
  64383. enumerable: true,
  64384. configurable: true
  64385. });
  64386. Object.defineProperty(HighlightLayer.prototype, "camera", {
  64387. /**
  64388. * Gets the camera attached to the layer.
  64389. */
  64390. get: function () {
  64391. return this._options.camera;
  64392. },
  64393. enumerable: true,
  64394. configurable: true
  64395. });
  64396. /**
  64397. * Creates the render target textures and post processes used in the highlight layer.
  64398. */
  64399. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  64400. var _this = this;
  64401. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  64402. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  64403. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  64404. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  64405. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  64406. width: this._mainTextureDesiredSize.width,
  64407. height: this._mainTextureDesiredSize.height
  64408. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64409. this._mainTexture.activeCamera = this._options.camera;
  64410. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64411. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64412. this._mainTexture.anisotropicFilteringLevel = 1;
  64413. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64414. this._mainTexture.renderParticles = false;
  64415. this._mainTexture.renderList = null;
  64416. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  64417. width: blurTextureWidth,
  64418. height: blurTextureHeight
  64419. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64420. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64421. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64422. this._blurTexture.anisotropicFilteringLevel = 16;
  64423. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64424. this._blurTexture.renderParticles = false;
  64425. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64426. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  64427. effect.setTexture("textureSampler", _this._mainTexture);
  64428. });
  64429. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  64430. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64431. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  64432. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64433. });
  64434. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64435. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  64436. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64437. });
  64438. }
  64439. else {
  64440. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64441. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  64442. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64443. });
  64444. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  64445. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  64446. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  64447. });
  64448. }
  64449. this._mainTexture.onAfterUnbindObservable.add(function () {
  64450. _this.onBeforeBlurObservable.notifyObservers(_this);
  64451. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  64452. _this.onAfterBlurObservable.notifyObservers(_this);
  64453. });
  64454. // Custom render function
  64455. var renderSubMesh = function (subMesh) {
  64456. var mesh = subMesh.getRenderingMesh();
  64457. var scene = _this._scene;
  64458. var engine = scene.getEngine();
  64459. // Culling
  64460. engine.setState(subMesh.getMaterial().backFaceCulling);
  64461. // Managing instances
  64462. var batch = mesh._getInstancesRenderList(subMesh._id);
  64463. if (batch.mustReturn) {
  64464. return;
  64465. }
  64466. // Excluded Mesh
  64467. if (_this._excludedMeshes[mesh.uniqueId]) {
  64468. return;
  64469. }
  64470. ;
  64471. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64472. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  64473. var material = subMesh.getMaterial();
  64474. var emissiveTexture = null;
  64475. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  64476. emissiveTexture = material.emissiveTexture;
  64477. }
  64478. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  64479. engine.enableEffect(_this._glowMapGenerationEffect);
  64480. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  64481. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  64482. if (highlightLayerMesh) {
  64483. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  64484. }
  64485. else {
  64486. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  64487. }
  64488. // Alpha test
  64489. if (material && material.needAlphaTesting()) {
  64490. var alphaTexture = material.getAlphaTestTexture();
  64491. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  64492. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64493. }
  64494. // Glow emissive only
  64495. if (emissiveTexture) {
  64496. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  64497. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  64498. }
  64499. // Bones
  64500. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64501. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64502. }
  64503. // Draw
  64504. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  64505. }
  64506. else {
  64507. // Need to reset refresh rate of the shadowMap
  64508. _this._mainTexture.resetRefreshCounter();
  64509. }
  64510. };
  64511. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  64512. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  64513. var index;
  64514. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64515. renderSubMesh(opaqueSubMeshes.data[index]);
  64516. }
  64517. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64518. renderSubMesh(alphaTestSubMeshes.data[index]);
  64519. }
  64520. for (index = 0; index < transparentSubMeshes.length; index++) {
  64521. renderSubMesh(transparentSubMeshes.data[index]);
  64522. }
  64523. };
  64524. this._mainTexture.onClearObservable.add(function (engine) {
  64525. engine.clear(HighlightLayer.neutralColor, true, true, true);
  64526. });
  64527. };
  64528. /**
  64529. * Checks for the readiness of the element composing the layer.
  64530. * @param subMesh the mesh to check for
  64531. * @param useInstances specify wether or not to use instances to render the mesh
  64532. * @param emissiveTexture the associated emissive texture used to generate the glow
  64533. * @return true if ready otherwise, false
  64534. */
  64535. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  64536. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  64537. return false;
  64538. }
  64539. var defines = [];
  64540. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64541. var mesh = subMesh.getMesh();
  64542. var material = subMesh.getMaterial();
  64543. var uv1 = false;
  64544. var uv2 = false;
  64545. // Alpha test
  64546. if (material && material.needAlphaTesting()) {
  64547. var alphaTexture = material.getAlphaTestTexture();
  64548. if (alphaTexture) {
  64549. defines.push("#define ALPHATEST");
  64550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  64551. alphaTexture.coordinatesIndex === 1) {
  64552. defines.push("#define DIFFUSEUV2");
  64553. uv2 = true;
  64554. }
  64555. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64556. defines.push("#define DIFFUSEUV1");
  64557. uv1 = true;
  64558. }
  64559. }
  64560. }
  64561. // Emissive
  64562. if (emissiveTexture) {
  64563. defines.push("#define EMISSIVE");
  64564. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  64565. emissiveTexture.coordinatesIndex === 1) {
  64566. defines.push("#define EMISSIVEUV2");
  64567. uv2 = true;
  64568. }
  64569. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64570. defines.push("#define EMISSIVEUV1");
  64571. uv1 = true;
  64572. }
  64573. }
  64574. if (uv1) {
  64575. attribs.push(BABYLON.VertexBuffer.UVKind);
  64576. defines.push("#define UV1");
  64577. }
  64578. if (uv2) {
  64579. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64580. defines.push("#define UV2");
  64581. }
  64582. // Bones
  64583. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64584. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64585. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64586. if (mesh.numBoneInfluencers > 4) {
  64587. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64588. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64589. }
  64590. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64591. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64592. }
  64593. else {
  64594. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64595. }
  64596. // Instances
  64597. if (useInstances) {
  64598. defines.push("#define INSTANCES");
  64599. attribs.push("world0");
  64600. attribs.push("world1");
  64601. attribs.push("world2");
  64602. attribs.push("world3");
  64603. }
  64604. // Get correct effect
  64605. var join = defines.join("\n");
  64606. if (this._cachedDefines !== join) {
  64607. this._cachedDefines = join;
  64608. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  64609. }
  64610. return this._glowMapGenerationEffect.isReady();
  64611. };
  64612. /**
  64613. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  64614. */
  64615. HighlightLayer.prototype.render = function () {
  64616. var currentEffect = this._glowMapMergeEffect;
  64617. // Check
  64618. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  64619. return;
  64620. var engine = this._scene.getEngine();
  64621. this.onBeforeComposeObservable.notifyObservers(this);
  64622. // Render
  64623. engine.enableEffect(currentEffect);
  64624. engine.setState(false);
  64625. // Cache
  64626. var previousStencilBuffer = engine.getStencilBuffer();
  64627. var previousStencilFunction = engine.getStencilFunction();
  64628. var previousStencilMask = engine.getStencilMask();
  64629. var previousStencilOperationPass = engine.getStencilOperationPass();
  64630. var previousStencilOperationFail = engine.getStencilOperationFail();
  64631. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  64632. var previousAlphaMode = engine.getAlphaMode();
  64633. // Texture
  64634. currentEffect.setTexture("textureSampler", this._blurTexture);
  64635. // VBOs
  64636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  64637. // Stencil operations
  64638. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  64639. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  64640. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  64641. // Draw order
  64642. engine.setAlphaMode(this._options.alphaBlendingMode);
  64643. engine.setStencilMask(0x00);
  64644. engine.setStencilBuffer(true);
  64645. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  64646. if (this.outerGlow) {
  64647. currentEffect.setFloat("offset", 0);
  64648. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  64649. engine.draw(true, 0, 6);
  64650. }
  64651. if (this.innerGlow) {
  64652. currentEffect.setFloat("offset", 1);
  64653. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  64654. engine.draw(true, 0, 6);
  64655. }
  64656. // Restore Cache
  64657. engine.setStencilFunction(previousStencilFunction);
  64658. engine.setStencilMask(previousStencilMask);
  64659. engine.setAlphaMode(previousAlphaMode);
  64660. engine.setStencilBuffer(previousStencilBuffer);
  64661. engine.setStencilOperationPass(previousStencilOperationPass);
  64662. engine.setStencilOperationFail(previousStencilOperationFail);
  64663. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  64664. engine._stencilState.reset();
  64665. this.onAfterComposeObservable.notifyObservers(this);
  64666. // Handle size changes.
  64667. var size = this._mainTexture.getSize();
  64668. this.setMainTextureSize();
  64669. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  64670. // Recreate RTT and post processes on size change.
  64671. this.onSizeChangedObservable.notifyObservers(this);
  64672. this.disposeTextureAndPostProcesses();
  64673. this.createTextureAndPostProcesses();
  64674. }
  64675. };
  64676. /**
  64677. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  64678. * @param mesh The mesh to exclude from the highlight layer
  64679. */
  64680. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  64681. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  64682. if (!meshExcluded) {
  64683. this._excludedMeshes[mesh.uniqueId] = {
  64684. mesh: mesh,
  64685. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  64686. mesh.getEngine().setStencilBuffer(false);
  64687. }),
  64688. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  64689. mesh.getEngine().setStencilBuffer(true);
  64690. }),
  64691. };
  64692. }
  64693. };
  64694. /**
  64695. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  64696. * @param mesh The mesh to highlight
  64697. */
  64698. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  64699. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  64700. if (meshExcluded) {
  64701. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  64702. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  64703. }
  64704. this._excludedMeshes[mesh.uniqueId] = undefined;
  64705. };
  64706. /**
  64707. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  64708. * @param mesh The mesh to highlight
  64709. * @param color The color of the highlight
  64710. * @param glowEmissiveOnly Extract the glow from the emissive texture
  64711. */
  64712. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  64713. var _this = this;
  64714. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  64715. var meshHighlight = this._meshes[mesh.uniqueId];
  64716. if (meshHighlight) {
  64717. meshHighlight.color = color;
  64718. }
  64719. else {
  64720. this._meshes[mesh.uniqueId] = {
  64721. mesh: mesh,
  64722. color: color,
  64723. // Lambda required for capture due to Observable this context
  64724. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  64725. if (_this._excludedMeshes[mesh.uniqueId]) {
  64726. _this.defaultStencilReference(mesh);
  64727. }
  64728. else {
  64729. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  64730. }
  64731. }),
  64732. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  64733. glowEmissiveOnly: glowEmissiveOnly
  64734. };
  64735. }
  64736. this._shouldRender = true;
  64737. };
  64738. /**
  64739. * Remove a mesh from the highlight layer in order to make it stop glowing.
  64740. * @param mesh The mesh to highlight
  64741. */
  64742. HighlightLayer.prototype.removeMesh = function (mesh) {
  64743. var meshHighlight = this._meshes[mesh.uniqueId];
  64744. if (meshHighlight) {
  64745. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  64746. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  64747. }
  64748. this._meshes[mesh.uniqueId] = undefined;
  64749. this._shouldRender = false;
  64750. for (var meshHighlightToCheck in this._meshes) {
  64751. if (meshHighlightToCheck) {
  64752. this._shouldRender = true;
  64753. break;
  64754. }
  64755. }
  64756. };
  64757. /**
  64758. * Returns true if the layer contains information to display, otherwise false.
  64759. */
  64760. HighlightLayer.prototype.shouldRender = function () {
  64761. return this.isEnabled && this._shouldRender;
  64762. };
  64763. /**
  64764. * Sets the main texture desired size which is the closest power of two
  64765. * of the engine canvas size.
  64766. */
  64767. HighlightLayer.prototype.setMainTextureSize = function () {
  64768. if (this._options.mainTextureFixedSize) {
  64769. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  64770. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  64771. }
  64772. else {
  64773. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  64774. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  64775. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  64776. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  64777. }
  64778. };
  64779. /**
  64780. * Force the stencil to the normal expected value for none glowing parts
  64781. */
  64782. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  64783. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  64784. };
  64785. /**
  64786. * Dispose only the render target textures and post process.
  64787. */
  64788. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  64789. this._blurTexture.dispose();
  64790. this._mainTexture.dispose();
  64791. this._downSamplePostprocess.dispose();
  64792. this._horizontalBlurPostprocess.dispose();
  64793. this._verticalBlurPostprocess.dispose();
  64794. };
  64795. /**
  64796. * Dispose the highlight layer and free resources.
  64797. */
  64798. HighlightLayer.prototype.dispose = function () {
  64799. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64800. if (vertexBuffer) {
  64801. vertexBuffer.dispose();
  64802. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64803. }
  64804. if (this._indexBuffer) {
  64805. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64806. this._indexBuffer = null;
  64807. }
  64808. // Clean textures and post processes
  64809. this.disposeTextureAndPostProcesses();
  64810. // Clean mesh references
  64811. for (var id in this._meshes) {
  64812. var meshHighlight = this._meshes[id];
  64813. if (meshHighlight && meshHighlight.mesh) {
  64814. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  64815. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  64816. }
  64817. }
  64818. this._meshes = null;
  64819. for (var id in this._excludedMeshes) {
  64820. var meshHighlight = this._excludedMeshes[id];
  64821. if (meshHighlight) {
  64822. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  64823. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  64824. }
  64825. }
  64826. this._excludedMeshes = null;
  64827. // Remove from scene
  64828. var index = this._scene.highlightLayers.indexOf(this, 0);
  64829. if (index > -1) {
  64830. this._scene.highlightLayers.splice(index, 1);
  64831. }
  64832. // Callback
  64833. this.onDisposeObservable.notifyObservers(this);
  64834. this.onDisposeObservable.clear();
  64835. this.onBeforeRenderMainTextureObservable.clear();
  64836. this.onBeforeBlurObservable.clear();
  64837. this.onBeforeComposeObservable.clear();
  64838. this.onAfterComposeObservable.clear();
  64839. this.onSizeChangedObservable.clear();
  64840. };
  64841. return HighlightLayer;
  64842. }());
  64843. /**
  64844. * The neutral color used during the preparation of the glow effect.
  64845. * This is black by default as the blend operation is a blend operation.
  64846. */
  64847. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  64848. /**
  64849. * Stencil value used for glowing meshes.
  64850. */
  64851. HighlightLayer.glowingMeshStencilReference = 0x02;
  64852. /**
  64853. * Stencil value used for the other meshes in the scene.
  64854. */
  64855. HighlightLayer.normalMeshStencilReference = 0x01;
  64856. BABYLON.HighlightLayer = HighlightLayer;
  64857. })(BABYLON || (BABYLON = {}));
  64858. //# sourceMappingURL=babylon.highlightlayer.js.map
  64859. var BABYLON;
  64860. (function (BABYLON) {
  64861. var MeshAssetTask = (function () {
  64862. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  64863. this.name = name;
  64864. this.meshesNames = meshesNames;
  64865. this.rootUrl = rootUrl;
  64866. this.sceneFilename = sceneFilename;
  64867. this.isCompleted = false;
  64868. }
  64869. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64870. var _this = this;
  64871. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  64872. _this.loadedMeshes = meshes;
  64873. _this.loadedParticleSystems = particleSystems;
  64874. _this.loadedSkeletons = skeletons;
  64875. _this.isCompleted = true;
  64876. if (_this.onSuccess) {
  64877. _this.onSuccess(_this);
  64878. }
  64879. onSuccess();
  64880. }, null, function () {
  64881. if (_this.onError) {
  64882. _this.onError(_this);
  64883. }
  64884. onError();
  64885. });
  64886. };
  64887. return MeshAssetTask;
  64888. }());
  64889. BABYLON.MeshAssetTask = MeshAssetTask;
  64890. var TextFileAssetTask = (function () {
  64891. function TextFileAssetTask(name, url) {
  64892. this.name = name;
  64893. this.url = url;
  64894. this.isCompleted = false;
  64895. }
  64896. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64897. var _this = this;
  64898. BABYLON.Tools.LoadFile(this.url, function (data) {
  64899. _this.text = data;
  64900. _this.isCompleted = true;
  64901. if (_this.onSuccess) {
  64902. _this.onSuccess(_this);
  64903. }
  64904. onSuccess();
  64905. }, null, scene.database, false, function () {
  64906. if (_this.onError) {
  64907. _this.onError(_this);
  64908. }
  64909. onError();
  64910. });
  64911. };
  64912. return TextFileAssetTask;
  64913. }());
  64914. BABYLON.TextFileAssetTask = TextFileAssetTask;
  64915. var BinaryFileAssetTask = (function () {
  64916. function BinaryFileAssetTask(name, url) {
  64917. this.name = name;
  64918. this.url = url;
  64919. this.isCompleted = false;
  64920. }
  64921. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64922. var _this = this;
  64923. BABYLON.Tools.LoadFile(this.url, function (data) {
  64924. _this.data = data;
  64925. _this.isCompleted = true;
  64926. if (_this.onSuccess) {
  64927. _this.onSuccess(_this);
  64928. }
  64929. onSuccess();
  64930. }, null, scene.database, true, function () {
  64931. if (_this.onError) {
  64932. _this.onError(_this);
  64933. }
  64934. onError();
  64935. });
  64936. };
  64937. return BinaryFileAssetTask;
  64938. }());
  64939. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  64940. var ImageAssetTask = (function () {
  64941. function ImageAssetTask(name, url) {
  64942. this.name = name;
  64943. this.url = url;
  64944. this.isCompleted = false;
  64945. }
  64946. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64947. var _this = this;
  64948. var img = new Image();
  64949. BABYLON.Tools.SetCorsBehavior(this.url, img);
  64950. img.onload = function () {
  64951. _this.image = img;
  64952. _this.isCompleted = true;
  64953. if (_this.onSuccess) {
  64954. _this.onSuccess(_this);
  64955. }
  64956. onSuccess();
  64957. };
  64958. img.onerror = function () {
  64959. if (_this.onError) {
  64960. _this.onError(_this);
  64961. }
  64962. onError();
  64963. };
  64964. img.src = this.url;
  64965. };
  64966. return ImageAssetTask;
  64967. }());
  64968. BABYLON.ImageAssetTask = ImageAssetTask;
  64969. var TextureAssetTask = (function () {
  64970. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  64971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64972. this.name = name;
  64973. this.url = url;
  64974. this.noMipmap = noMipmap;
  64975. this.invertY = invertY;
  64976. this.samplingMode = samplingMode;
  64977. this.isCompleted = false;
  64978. }
  64979. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  64980. var _this = this;
  64981. var onload = function () {
  64982. _this.isCompleted = true;
  64983. if (_this.onSuccess) {
  64984. _this.onSuccess(_this);
  64985. }
  64986. onSuccess();
  64987. };
  64988. var onerror = function () {
  64989. if (_this.onError) {
  64990. _this.onError(_this);
  64991. }
  64992. onError();
  64993. };
  64994. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  64995. };
  64996. return TextureAssetTask;
  64997. }());
  64998. BABYLON.TextureAssetTask = TextureAssetTask;
  64999. var CubeTextureAssetTask = (function () {
  65000. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  65001. this.name = name;
  65002. this.url = url;
  65003. this.extensions = extensions;
  65004. this.noMipmap = noMipmap;
  65005. this.files = files;
  65006. this.isCompleted = false;
  65007. }
  65008. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  65009. var _this = this;
  65010. var onload = function () {
  65011. _this.isCompleted = true;
  65012. if (_this.onSuccess) {
  65013. _this.onSuccess(_this);
  65014. }
  65015. onSuccess();
  65016. };
  65017. var onerror = function () {
  65018. if (_this.onError) {
  65019. _this.onError(_this);
  65020. }
  65021. onError();
  65022. };
  65023. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  65024. };
  65025. return CubeTextureAssetTask;
  65026. }());
  65027. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  65028. var HDRCubeTextureAssetTask = (function () {
  65029. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  65030. if (noMipmap === void 0) { noMipmap = false; }
  65031. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65032. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65033. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65034. this.name = name;
  65035. this.url = url;
  65036. this.size = size;
  65037. this.noMipmap = noMipmap;
  65038. this.generateHarmonics = generateHarmonics;
  65039. this.useInGammaSpace = useInGammaSpace;
  65040. this.usePMREMGenerator = usePMREMGenerator;
  65041. this.isCompleted = false;
  65042. }
  65043. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  65044. var _this = this;
  65045. var onload = function () {
  65046. _this.isCompleted = true;
  65047. if (_this.onSuccess) {
  65048. _this.onSuccess(_this);
  65049. }
  65050. onSuccess();
  65051. };
  65052. var onerror = function () {
  65053. if (_this.onError) {
  65054. _this.onError(_this);
  65055. }
  65056. onError();
  65057. };
  65058. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  65059. };
  65060. return HDRCubeTextureAssetTask;
  65061. }());
  65062. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  65063. var AssetsManager = (function () {
  65064. function AssetsManager(scene) {
  65065. this.tasks = new Array();
  65066. this.waitingTasksCount = 0;
  65067. this.useDefaultLoadingScreen = true;
  65068. this._scene = scene;
  65069. }
  65070. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  65071. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  65072. this.tasks.push(task);
  65073. return task;
  65074. };
  65075. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  65076. var task = new TextFileAssetTask(taskName, url);
  65077. this.tasks.push(task);
  65078. return task;
  65079. };
  65080. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  65081. var task = new BinaryFileAssetTask(taskName, url);
  65082. this.tasks.push(task);
  65083. return task;
  65084. };
  65085. AssetsManager.prototype.addImageTask = function (taskName, url) {
  65086. var task = new ImageAssetTask(taskName, url);
  65087. this.tasks.push(task);
  65088. return task;
  65089. };
  65090. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  65091. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65092. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  65093. this.tasks.push(task);
  65094. return task;
  65095. };
  65096. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  65097. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  65098. this.tasks.push(task);
  65099. return task;
  65100. };
  65101. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  65102. if (noMipmap === void 0) { noMipmap = false; }
  65103. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65104. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65105. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65106. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  65107. this.tasks.push(task);
  65108. return task;
  65109. };
  65110. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  65111. this.waitingTasksCount--;
  65112. if (this.waitingTasksCount === 0) {
  65113. if (this.onFinish) {
  65114. this.onFinish(this.tasks);
  65115. }
  65116. this._scene.getEngine().hideLoadingUI();
  65117. }
  65118. };
  65119. AssetsManager.prototype._runTask = function (task) {
  65120. var _this = this;
  65121. task.run(this._scene, function () {
  65122. if (_this.onTaskSuccess) {
  65123. _this.onTaskSuccess(task);
  65124. }
  65125. _this._decreaseWaitingTasksCount();
  65126. }, function () {
  65127. if (_this.onTaskError) {
  65128. _this.onTaskError(task);
  65129. }
  65130. _this._decreaseWaitingTasksCount();
  65131. });
  65132. };
  65133. AssetsManager.prototype.reset = function () {
  65134. this.tasks = new Array();
  65135. return this;
  65136. };
  65137. AssetsManager.prototype.load = function () {
  65138. this.waitingTasksCount = this.tasks.length;
  65139. if (this.waitingTasksCount === 0) {
  65140. if (this.onFinish) {
  65141. this.onFinish(this.tasks);
  65142. }
  65143. return this;
  65144. }
  65145. if (this.useDefaultLoadingScreen) {
  65146. this._scene.getEngine().displayLoadingUI();
  65147. }
  65148. for (var index = 0; index < this.tasks.length; index++) {
  65149. var task = this.tasks[index];
  65150. this._runTask(task);
  65151. }
  65152. return this;
  65153. };
  65154. return AssetsManager;
  65155. }());
  65156. BABYLON.AssetsManager = AssetsManager;
  65157. })(BABYLON || (BABYLON = {}));
  65158. //# sourceMappingURL=babylon.assetsManager.js.map
  65159. var BABYLON;
  65160. (function (BABYLON) {
  65161. var MapTexture = (function (_super) {
  65162. __extends(MapTexture, _super);
  65163. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  65164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65165. if (useMipMap === void 0) { useMipMap = false; }
  65166. if (margin === void 0) { margin = 0; }
  65167. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  65168. _this.name = name;
  65169. _this._size = size;
  65170. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65171. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65172. // Create the rectPackMap that will allocate portion of the texture
  65173. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  65174. // Create the texture that will store the content
  65175. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  65176. return _this;
  65177. }
  65178. /**
  65179. * Allocate a rectangle of a given size in the texture map
  65180. * @param size the size of the rectangle to allocation
  65181. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  65182. */
  65183. MapTexture.prototype.allocateRect = function (size) {
  65184. return this._rectPackingMap.addRect(size);
  65185. };
  65186. /**
  65187. * Free a given rectangle from the texture map
  65188. * @param rectInfo the instance corresponding to the rect to free.
  65189. */
  65190. MapTexture.prototype.freeRect = function (rectInfo) {
  65191. if (rectInfo) {
  65192. rectInfo.freeContent();
  65193. }
  65194. };
  65195. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  65196. /**
  65197. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  65198. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  65199. * @returns {}
  65200. */
  65201. get: function () {
  65202. return this._rectPackingMap.freeSpace;
  65203. },
  65204. enumerable: true,
  65205. configurable: true
  65206. });
  65207. /**
  65208. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  65209. * 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.
  65210. * Don't forget to call unbindTexture when you're done rendering
  65211. * @param rect the zone to render to
  65212. * @param clear true to clear the portion's color/depth data
  65213. */
  65214. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  65215. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  65216. };
  65217. /**
  65218. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  65219. * 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.
  65220. * Don't forget to call unbindTexture when you're done rendering
  65221. * @param pos the position into the texture
  65222. * @param size the portion to fit the clip space to
  65223. * @param clear true to clear the portion's color/depth data
  65224. */
  65225. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  65226. var engine = this.getScene().getEngine();
  65227. engine.bindFramebuffer(this._texture);
  65228. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  65229. if (clear) {
  65230. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  65231. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  65232. }
  65233. };
  65234. /**
  65235. * Unbind the texture map from the rendering engine.
  65236. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  65237. * @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.
  65238. */
  65239. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  65240. // Dump ?
  65241. if (dumpForDebug) {
  65242. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  65243. }
  65244. var engine = this.getScene().getEngine();
  65245. if (this._replacedViewport) {
  65246. engine.setViewport(this._replacedViewport);
  65247. this._replacedViewport = null;
  65248. }
  65249. engine.unBindFramebuffer(this._texture);
  65250. };
  65251. Object.defineProperty(MapTexture.prototype, "canRescale", {
  65252. get: function () {
  65253. return false;
  65254. },
  65255. enumerable: true,
  65256. configurable: true
  65257. });
  65258. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  65259. // Anyway, there's not much point to use this method for this kind of texture I guess
  65260. MapTexture.prototype.clone = function () {
  65261. return null;
  65262. };
  65263. return MapTexture;
  65264. }(BABYLON.Texture));
  65265. BABYLON.MapTexture = MapTexture;
  65266. })(BABYLON || (BABYLON = {}));
  65267. //# sourceMappingURL=babylon.mapTexture.js.map
  65268. var BABYLON;
  65269. (function (BABYLON) {
  65270. /**
  65271. * This class describe a rectangle that were added to the map.
  65272. * You have access to its coordinates either in pixel or normalized (UV)
  65273. */
  65274. var PackedRect = (function () {
  65275. function PackedRect(root, parent, pos, size) {
  65276. this._pos = pos;
  65277. this._size = size;
  65278. this._root = root;
  65279. this._parent = parent;
  65280. this._contentSize = null;
  65281. this._bottomNode = null;
  65282. this._leftNode = null;
  65283. this._initialSize = null;
  65284. this._rightNode = null;
  65285. }
  65286. Object.defineProperty(PackedRect.prototype, "pos", {
  65287. /**
  65288. * @returns the position of this node into the map
  65289. */
  65290. get: function () {
  65291. return this._pos;
  65292. },
  65293. enumerable: true,
  65294. configurable: true
  65295. });
  65296. Object.defineProperty(PackedRect.prototype, "contentSize", {
  65297. /**
  65298. * @returns the size of the rectangle this node handles
  65299. */
  65300. get: function () {
  65301. return this._contentSize;
  65302. },
  65303. enumerable: true,
  65304. configurable: true
  65305. });
  65306. /**
  65307. * Retrieve the inner position (considering the margin) and stores it into the res object
  65308. * @param res must be a valid Vector2 that will contain the inner position after this call
  65309. */
  65310. PackedRect.prototype.getInnerPosToRef = function (res) {
  65311. var m = this._root._margin;
  65312. res.x = this._pos.x + m;
  65313. res.y = this._pos.y + m;
  65314. };
  65315. /**
  65316. * Retrieve the inner size (considering the margin) and stores it into the res object
  65317. * @param res must be a valid Size that will contain the inner size after this call
  65318. */
  65319. PackedRect.prototype.getInnerSizeToRef = function (res) {
  65320. var m = this._root._margin;
  65321. res.width = this._contentSize.width - (m * 2);
  65322. res.height = this._contentSize.height - (m * 2);
  65323. };
  65324. Object.defineProperty(PackedRect.prototype, "UVs", {
  65325. /**
  65326. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  65327. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  65328. */
  65329. get: function () {
  65330. if (!this._contentSize) {
  65331. throw new Error("Can't compute UVs for this object because it's nor allocated");
  65332. }
  65333. return this.getUVsForCustomSize(this._contentSize);
  65334. },
  65335. enumerable: true,
  65336. configurable: true
  65337. });
  65338. /**
  65339. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  65340. * and then using only a part of the PackRect.
  65341. * This method will return the UVs for this part by given the custom size of what you really use
  65342. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  65343. */
  65344. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  65345. var mainWidth = this._root._size.width;
  65346. var mainHeight = this._root._size.height;
  65347. var margin = this._root._margin;
  65348. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  65349. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  65350. var uvs = new Array();
  65351. uvs.push(topLeft);
  65352. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  65353. uvs.push(rightBottom);
  65354. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  65355. return uvs;
  65356. };
  65357. /**
  65358. * Free this rectangle from the map.
  65359. * Call this method when you no longer need the rectangle to be in the map.
  65360. */
  65361. PackedRect.prototype.freeContent = function () {
  65362. if (!this.contentSize) {
  65363. return;
  65364. }
  65365. this._contentSize = null;
  65366. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  65367. this.attemptDefrag();
  65368. };
  65369. Object.defineProperty(PackedRect.prototype, "isUsed", {
  65370. get: function () {
  65371. return this._contentSize != null || this._leftNode != null;
  65372. },
  65373. enumerable: true,
  65374. configurable: true
  65375. });
  65376. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  65377. var node = this.findNode(contentSize);
  65378. // Not enough space...
  65379. if (!node) {
  65380. return null;
  65381. }
  65382. node.splitNode(contentSize);
  65383. return node;
  65384. };
  65385. PackedRect.prototype.findNode = function (size) {
  65386. var resNode = null;
  65387. var margin = this._root._margin * 2;
  65388. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  65389. if (this.isUsed) {
  65390. if (this._leftNode) {
  65391. resNode = this._leftNode.findNode(size);
  65392. }
  65393. if (!resNode && this._rightNode) {
  65394. resNode = this._rightNode.findNode(size);
  65395. }
  65396. if (!resNode && this._bottomNode) {
  65397. resNode = this._bottomNode.findNode(size);
  65398. }
  65399. }
  65400. else if (this._initialSize) {
  65401. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  65402. resNode = this;
  65403. }
  65404. else {
  65405. return null;
  65406. }
  65407. }
  65408. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  65409. resNode = this;
  65410. }
  65411. return resNode;
  65412. };
  65413. PackedRect.prototype.splitNode = function (contentSize) {
  65414. var cs = PackedRect.TpsSize;
  65415. var margin = this._root._margin * 2;
  65416. cs.copyFrom(contentSize);
  65417. cs.width += margin;
  65418. cs.height += margin;
  65419. // 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)
  65420. if (!this._contentSize && this._initialSize) {
  65421. this._contentSize = cs.clone();
  65422. 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));
  65423. return this._leftNode.splitNode(contentSize);
  65424. }
  65425. else {
  65426. this._contentSize = cs.clone();
  65427. this._initialSize = cs.clone();
  65428. if (cs.width !== this._size.width) {
  65429. 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));
  65430. }
  65431. if (cs.height !== this._size.height) {
  65432. 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));
  65433. }
  65434. return this;
  65435. }
  65436. };
  65437. PackedRect.prototype.attemptDefrag = function () {
  65438. if (!this.isUsed && this.isRecursiveFree) {
  65439. this.clearNode();
  65440. if (this._parent) {
  65441. this._parent.attemptDefrag();
  65442. }
  65443. }
  65444. };
  65445. PackedRect.prototype.clearNode = function () {
  65446. this._initialSize = null;
  65447. this._rightNode = null;
  65448. this._bottomNode = null;
  65449. };
  65450. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  65451. get: function () {
  65452. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  65453. },
  65454. enumerable: true,
  65455. configurable: true
  65456. });
  65457. PackedRect.prototype.evalFreeSize = function (size) {
  65458. var levelSize = 0;
  65459. if (!this.isUsed) {
  65460. var margin = this._root._margin;
  65461. var is = this._initialSize;
  65462. if (is) {
  65463. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  65464. }
  65465. else {
  65466. var size_1 = this._size;
  65467. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  65468. }
  65469. }
  65470. if (this._rightNode) {
  65471. levelSize += this._rightNode.evalFreeSize(0);
  65472. }
  65473. if (this._bottomNode) {
  65474. levelSize += this._bottomNode.evalFreeSize(0);
  65475. }
  65476. return levelSize + size;
  65477. };
  65478. return PackedRect;
  65479. }());
  65480. PackedRect.TpsSize = BABYLON.Size.Zero();
  65481. BABYLON.PackedRect = PackedRect;
  65482. /**
  65483. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  65484. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  65485. * 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.
  65486. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  65487. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  65488. */
  65489. var RectPackingMap = (function (_super) {
  65490. __extends(RectPackingMap, _super);
  65491. /**
  65492. * Create an instance of the object with a dimension using the given size
  65493. * @param size The dimension of the rectangle that will contain all the sub ones.
  65494. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  65495. */
  65496. function RectPackingMap(size, margin) {
  65497. if (margin === void 0) { margin = 0; }
  65498. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  65499. _this._margin = margin;
  65500. _this._root = _this;
  65501. return _this;
  65502. }
  65503. /**
  65504. * Add a rectangle, finding the best location to store it into the map
  65505. * @param size the dimension of the rectangle to store
  65506. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  65507. */
  65508. RectPackingMap.prototype.addRect = function (size) {
  65509. var node = this.findAndSplitNode(size);
  65510. return node;
  65511. };
  65512. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  65513. /**
  65514. * Return the current space free normalized between [0;1]
  65515. * @returns {}
  65516. */
  65517. get: function () {
  65518. var freeSize = 0;
  65519. freeSize = this.evalFreeSize(freeSize);
  65520. return freeSize / (this._size.width * this._size.height);
  65521. },
  65522. enumerable: true,
  65523. configurable: true
  65524. });
  65525. return RectPackingMap;
  65526. }(PackedRect));
  65527. BABYLON.RectPackingMap = RectPackingMap;
  65528. })(BABYLON || (BABYLON = {}));
  65529. //# sourceMappingURL=babylon.rectPackingMap.js.map
  65530. var BABYLON;
  65531. (function (BABYLON) {
  65532. var serializedGeometries = [];
  65533. var serializeGeometry = function (geometry, serializationGeometries) {
  65534. if (serializedGeometries[geometry.id]) {
  65535. return;
  65536. }
  65537. if (geometry.doNotSerialize) {
  65538. return;
  65539. }
  65540. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  65541. serializationGeometries.boxes.push(geometry.serialize());
  65542. }
  65543. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  65544. serializationGeometries.spheres.push(geometry.serialize());
  65545. }
  65546. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  65547. serializationGeometries.cylinders.push(geometry.serialize());
  65548. }
  65549. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  65550. serializationGeometries.toruses.push(geometry.serialize());
  65551. }
  65552. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  65553. serializationGeometries.grounds.push(geometry.serialize());
  65554. }
  65555. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  65556. serializationGeometries.planes.push(geometry.serialize());
  65557. }
  65558. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  65559. serializationGeometries.torusKnots.push(geometry.serialize());
  65560. }
  65561. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  65562. throw new Error("Unknown primitive type");
  65563. }
  65564. else {
  65565. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  65566. }
  65567. serializedGeometries[geometry.id] = true;
  65568. };
  65569. var serializeMesh = function (mesh, serializationScene) {
  65570. var serializationObject = {};
  65571. // Geometry
  65572. var geometry = mesh._geometry;
  65573. if (geometry) {
  65574. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  65575. // 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
  65576. serializeGeometry(geometry, serializationScene.geometries);
  65577. }
  65578. }
  65579. // Custom
  65580. if (mesh.serialize) {
  65581. mesh.serialize(serializationObject);
  65582. }
  65583. return serializationObject;
  65584. };
  65585. var finalizeSingleMesh = function (mesh, serializationObject) {
  65586. //only works if the mesh is already loaded
  65587. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  65588. //serialize material
  65589. if (mesh.material) {
  65590. if (mesh.material instanceof BABYLON.StandardMaterial) {
  65591. serializationObject.materials = serializationObject.materials || [];
  65592. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  65593. serializationObject.materials.push(mesh.material.serialize());
  65594. }
  65595. }
  65596. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  65597. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  65598. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  65599. serializationObject.multiMaterials.push(mesh.material.serialize());
  65600. }
  65601. }
  65602. }
  65603. //serialize geometry
  65604. var geometry = mesh._geometry;
  65605. if (geometry) {
  65606. if (!serializationObject.geometries) {
  65607. serializationObject.geometries = {};
  65608. serializationObject.geometries.boxes = [];
  65609. serializationObject.geometries.spheres = [];
  65610. serializationObject.geometries.cylinders = [];
  65611. serializationObject.geometries.toruses = [];
  65612. serializationObject.geometries.grounds = [];
  65613. serializationObject.geometries.planes = [];
  65614. serializationObject.geometries.torusKnots = [];
  65615. serializationObject.geometries.vertexData = [];
  65616. }
  65617. serializeGeometry(geometry, serializationObject.geometries);
  65618. }
  65619. // Skeletons
  65620. if (mesh.skeleton) {
  65621. serializationObject.skeletons = serializationObject.skeletons || [];
  65622. serializationObject.skeletons.push(mesh.skeleton.serialize());
  65623. }
  65624. //serialize the actual mesh
  65625. serializationObject.meshes = serializationObject.meshes || [];
  65626. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  65627. }
  65628. };
  65629. var SceneSerializer = (function () {
  65630. function SceneSerializer() {
  65631. }
  65632. SceneSerializer.ClearCache = function () {
  65633. serializedGeometries = [];
  65634. };
  65635. SceneSerializer.Serialize = function (scene) {
  65636. var serializationObject = {};
  65637. SceneSerializer.ClearCache();
  65638. // Scene
  65639. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  65640. serializationObject.autoClear = scene.autoClear;
  65641. serializationObject.clearColor = scene.clearColor.asArray();
  65642. serializationObject.ambientColor = scene.ambientColor.asArray();
  65643. serializationObject.gravity = scene.gravity.asArray();
  65644. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  65645. serializationObject.workerCollisions = scene.workerCollisions;
  65646. // Fog
  65647. if (scene.fogMode && scene.fogMode !== 0) {
  65648. serializationObject.fogMode = scene.fogMode;
  65649. serializationObject.fogColor = scene.fogColor.asArray();
  65650. serializationObject.fogStart = scene.fogStart;
  65651. serializationObject.fogEnd = scene.fogEnd;
  65652. serializationObject.fogDensity = scene.fogDensity;
  65653. }
  65654. //Physics
  65655. if (scene.isPhysicsEnabled()) {
  65656. serializationObject.physicsEnabled = true;
  65657. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  65658. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  65659. }
  65660. // Metadata
  65661. if (scene.metadata) {
  65662. serializationObject.metadata = scene.metadata;
  65663. }
  65664. // Morph targets
  65665. serializationObject.morphTargetManagers = [];
  65666. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  65667. var abstractMesh = _a[_i];
  65668. var manager = abstractMesh.morphTargetManager;
  65669. if (manager) {
  65670. serializationObject.morphTargetManagers.push(manager.serialize());
  65671. }
  65672. }
  65673. // Lights
  65674. serializationObject.lights = [];
  65675. var index;
  65676. var light;
  65677. for (index = 0; index < scene.lights.length; index++) {
  65678. light = scene.lights[index];
  65679. if (!light.doNotSerialize) {
  65680. serializationObject.lights.push(light.serialize());
  65681. }
  65682. }
  65683. // Cameras
  65684. serializationObject.cameras = [];
  65685. for (index = 0; index < scene.cameras.length; index++) {
  65686. var camera = scene.cameras[index];
  65687. if (!camera.doNotSerialize) {
  65688. serializationObject.cameras.push(camera.serialize());
  65689. }
  65690. }
  65691. if (scene.activeCamera) {
  65692. serializationObject.activeCameraID = scene.activeCamera.id;
  65693. }
  65694. // Animations
  65695. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  65696. // Materials
  65697. serializationObject.materials = [];
  65698. serializationObject.multiMaterials = [];
  65699. var material;
  65700. for (index = 0; index < scene.materials.length; index++) {
  65701. material = scene.materials[index];
  65702. if (!material.doNotSerialize) {
  65703. serializationObject.materials.push(material.serialize());
  65704. }
  65705. }
  65706. // MultiMaterials
  65707. serializationObject.multiMaterials = [];
  65708. for (index = 0; index < scene.multiMaterials.length; index++) {
  65709. var multiMaterial = scene.multiMaterials[index];
  65710. serializationObject.multiMaterials.push(multiMaterial.serialize());
  65711. }
  65712. // Skeletons
  65713. serializationObject.skeletons = [];
  65714. for (index = 0; index < scene.skeletons.length; index++) {
  65715. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  65716. }
  65717. // Geometries
  65718. serializationObject.geometries = {};
  65719. serializationObject.geometries.boxes = [];
  65720. serializationObject.geometries.spheres = [];
  65721. serializationObject.geometries.cylinders = [];
  65722. serializationObject.geometries.toruses = [];
  65723. serializationObject.geometries.grounds = [];
  65724. serializationObject.geometries.planes = [];
  65725. serializationObject.geometries.torusKnots = [];
  65726. serializationObject.geometries.vertexData = [];
  65727. serializedGeometries = [];
  65728. var geometries = scene.getGeometries();
  65729. for (index = 0; index < geometries.length; index++) {
  65730. var geometry = geometries[index];
  65731. if (geometry.isReady()) {
  65732. serializeGeometry(geometry, serializationObject.geometries);
  65733. }
  65734. }
  65735. // Meshes
  65736. serializationObject.meshes = [];
  65737. for (index = 0; index < scene.meshes.length; index++) {
  65738. var abstractMesh = scene.meshes[index];
  65739. if (abstractMesh instanceof BABYLON.Mesh) {
  65740. var mesh = abstractMesh;
  65741. if (!mesh.doNotSerialize) {
  65742. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  65743. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  65744. }
  65745. }
  65746. }
  65747. }
  65748. // Particles Systems
  65749. serializationObject.particleSystems = [];
  65750. for (index = 0; index < scene.particleSystems.length; index++) {
  65751. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  65752. }
  65753. // Lens flares
  65754. serializationObject.lensFlareSystems = [];
  65755. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  65756. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  65757. }
  65758. // Shadows
  65759. serializationObject.shadowGenerators = [];
  65760. for (index = 0; index < scene.lights.length; index++) {
  65761. light = scene.lights[index];
  65762. var shadowGenerator = light.getShadowGenerator();
  65763. if (shadowGenerator) {
  65764. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  65765. }
  65766. }
  65767. // Action Manager
  65768. if (scene.actionManager) {
  65769. serializationObject.actions = scene.actionManager.serialize("scene");
  65770. }
  65771. // Audio
  65772. serializationObject.sounds = [];
  65773. for (index = 0; index < scene.soundTracks.length; index++) {
  65774. var soundtrack = scene.soundTracks[index];
  65775. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  65776. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  65777. }
  65778. }
  65779. return serializationObject;
  65780. };
  65781. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  65782. if (withParents === void 0) { withParents = false; }
  65783. if (withChildren === void 0) { withChildren = false; }
  65784. var serializationObject = {};
  65785. SceneSerializer.ClearCache();
  65786. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  65787. if (withParents || withChildren) {
  65788. //deliberate for loop! not for each, appended should be processed as well.
  65789. for (var i = 0; i < toSerialize.length; ++i) {
  65790. if (withChildren) {
  65791. toSerialize[i].getDescendants().forEach(function (node) {
  65792. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  65793. toSerialize.push(node);
  65794. }
  65795. });
  65796. }
  65797. //make sure the array doesn't contain the object already
  65798. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  65799. toSerialize.push(toSerialize[i].parent);
  65800. }
  65801. }
  65802. }
  65803. toSerialize.forEach(function (mesh) {
  65804. finalizeSingleMesh(mesh, serializationObject);
  65805. });
  65806. return serializationObject;
  65807. };
  65808. return SceneSerializer;
  65809. }());
  65810. BABYLON.SceneSerializer = SceneSerializer;
  65811. })(BABYLON || (BABYLON = {}));
  65812. //# sourceMappingURL=babylon.sceneSerializer.js.map
  65813. var BABYLON;
  65814. (function (BABYLON) {
  65815. var ReflectionProbe = (function () {
  65816. function ReflectionProbe(name, size, scene, generateMipMaps) {
  65817. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65818. var _this = this;
  65819. this.name = name;
  65820. this._viewMatrix = BABYLON.Matrix.Identity();
  65821. this._target = BABYLON.Vector3.Zero();
  65822. this._add = BABYLON.Vector3.Zero();
  65823. this.invertYAxis = false;
  65824. this.position = BABYLON.Vector3.Zero();
  65825. this._scene = scene;
  65826. this._scene.reflectionProbes.push(this);
  65827. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  65828. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  65829. switch (faceIndex) {
  65830. case 0:
  65831. _this._add.copyFromFloats(1, 0, 0);
  65832. break;
  65833. case 1:
  65834. _this._add.copyFromFloats(-1, 0, 0);
  65835. break;
  65836. case 2:
  65837. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  65838. break;
  65839. case 3:
  65840. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  65841. break;
  65842. case 4:
  65843. _this._add.copyFromFloats(0, 0, 1);
  65844. break;
  65845. case 5:
  65846. _this._add.copyFromFloats(0, 0, -1);
  65847. break;
  65848. }
  65849. if (_this._attachedMesh) {
  65850. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  65851. }
  65852. _this.position.addToRef(_this._add, _this._target);
  65853. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  65854. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  65855. });
  65856. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  65857. scene.updateTransformMatrix(true);
  65858. });
  65859. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  65860. }
  65861. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  65862. get: function () {
  65863. return this._renderTargetTexture.samples;
  65864. },
  65865. set: function (value) {
  65866. this._renderTargetTexture.samples = value;
  65867. },
  65868. enumerable: true,
  65869. configurable: true
  65870. });
  65871. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  65872. get: function () {
  65873. return this._renderTargetTexture.refreshRate;
  65874. },
  65875. set: function (value) {
  65876. this._renderTargetTexture.refreshRate = value;
  65877. },
  65878. enumerable: true,
  65879. configurable: true
  65880. });
  65881. ReflectionProbe.prototype.getScene = function () {
  65882. return this._scene;
  65883. };
  65884. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  65885. get: function () {
  65886. return this._renderTargetTexture;
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  65892. get: function () {
  65893. return this._renderTargetTexture.renderList;
  65894. },
  65895. enumerable: true,
  65896. configurable: true
  65897. });
  65898. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  65899. this._attachedMesh = mesh;
  65900. };
  65901. ReflectionProbe.prototype.dispose = function () {
  65902. var index = this._scene.reflectionProbes.indexOf(this);
  65903. if (index !== -1) {
  65904. // Remove from the scene if found
  65905. this._scene.reflectionProbes.splice(index, 1);
  65906. }
  65907. if (this._renderTargetTexture) {
  65908. this._renderTargetTexture.dispose();
  65909. this._renderTargetTexture = null;
  65910. }
  65911. };
  65912. return ReflectionProbe;
  65913. }());
  65914. BABYLON.ReflectionProbe = ReflectionProbe;
  65915. })(BABYLON || (BABYLON = {}));
  65916. //# sourceMappingURL=babylon.reflectionProbe.js.map
  65917. var BABYLON;
  65918. (function (BABYLON) {
  65919. var Layer = (function () {
  65920. function Layer(name, imgUrl, scene, isBackground, color) {
  65921. this.name = name;
  65922. this.scale = new BABYLON.Vector2(1, 1);
  65923. this.offset = new BABYLON.Vector2(0, 0);
  65924. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  65925. this.layerMask = 0x0FFFFFFF;
  65926. this._vertexBuffers = {};
  65927. // Events
  65928. /**
  65929. * An event triggered when the layer is disposed.
  65930. * @type {BABYLON.Observable}
  65931. */
  65932. this.onDisposeObservable = new BABYLON.Observable();
  65933. /**
  65934. * An event triggered before rendering the scene
  65935. * @type {BABYLON.Observable}
  65936. */
  65937. this.onBeforeRenderObservable = new BABYLON.Observable();
  65938. /**
  65939. * An event triggered after rendering the scene
  65940. * @type {BABYLON.Observable}
  65941. */
  65942. this.onAfterRenderObservable = new BABYLON.Observable();
  65943. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  65944. this.isBackground = isBackground === undefined ? true : isBackground;
  65945. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  65946. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65947. this._scene.layers.push(this);
  65948. var engine = this._scene.getEngine();
  65949. // VBO
  65950. var vertices = [];
  65951. vertices.push(1, 1);
  65952. vertices.push(-1, 1);
  65953. vertices.push(-1, -1);
  65954. vertices.push(1, -1);
  65955. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65956. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  65957. // Indices
  65958. var indices = [];
  65959. indices.push(0);
  65960. indices.push(1);
  65961. indices.push(2);
  65962. indices.push(0);
  65963. indices.push(2);
  65964. indices.push(3);
  65965. this._indexBuffer = engine.createIndexBuffer(indices);
  65966. // Effects
  65967. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  65968. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  65969. }
  65970. Object.defineProperty(Layer.prototype, "onDispose", {
  65971. set: function (callback) {
  65972. if (this._onDisposeObserver) {
  65973. this.onDisposeObservable.remove(this._onDisposeObserver);
  65974. }
  65975. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  65976. },
  65977. enumerable: true,
  65978. configurable: true
  65979. });
  65980. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  65981. set: function (callback) {
  65982. if (this._onBeforeRenderObserver) {
  65983. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65984. }
  65985. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65986. },
  65987. enumerable: true,
  65988. configurable: true
  65989. });
  65990. Object.defineProperty(Layer.prototype, "onAfterRender", {
  65991. set: function (callback) {
  65992. if (this._onAfterRenderObserver) {
  65993. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65994. }
  65995. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65996. },
  65997. enumerable: true,
  65998. configurable: true
  65999. });
  66000. Layer.prototype.render = function () {
  66001. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  66002. // Check
  66003. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  66004. return;
  66005. var engine = this._scene.getEngine();
  66006. this.onBeforeRenderObservable.notifyObservers(this);
  66007. // Render
  66008. engine.enableEffect(currentEffect);
  66009. engine.setState(false);
  66010. // Texture
  66011. currentEffect.setTexture("textureSampler", this.texture);
  66012. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  66013. // Color
  66014. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  66015. // Scale / offset
  66016. currentEffect.setVector2("offset", this.offset);
  66017. currentEffect.setVector2("scale", this.scale);
  66018. // VBOs
  66019. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  66020. // Draw order
  66021. if (!this.alphaTest) {
  66022. engine.setAlphaMode(this.alphaBlendingMode);
  66023. engine.draw(true, 0, 6);
  66024. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66025. }
  66026. else {
  66027. engine.draw(true, 0, 6);
  66028. }
  66029. this.onAfterRenderObservable.notifyObservers(this);
  66030. };
  66031. Layer.prototype.dispose = function () {
  66032. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66033. if (vertexBuffer) {
  66034. vertexBuffer.dispose();
  66035. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66036. }
  66037. if (this._indexBuffer) {
  66038. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66039. this._indexBuffer = null;
  66040. }
  66041. if (this.texture) {
  66042. this.texture.dispose();
  66043. this.texture = null;
  66044. }
  66045. // Remove from scene
  66046. var index = this._scene.layers.indexOf(this);
  66047. this._scene.layers.splice(index, 1);
  66048. // Callback
  66049. this.onDisposeObservable.notifyObservers(this);
  66050. this.onDisposeObservable.clear();
  66051. this.onAfterRenderObservable.clear();
  66052. this.onBeforeRenderObservable.clear();
  66053. };
  66054. return Layer;
  66055. }());
  66056. BABYLON.Layer = Layer;
  66057. })(BABYLON || (BABYLON = {}));
  66058. //# sourceMappingURL=babylon.layer.js.map
  66059. 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#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\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#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\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;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\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\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*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\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=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=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 EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+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\n#ifdef LDROUTPUT\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#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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 FLOAT\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#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\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","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\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#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\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 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}","geometryVertexShader":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*finalWorld*vec4(position,1.0);\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}","geometryPixelShader":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,0.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\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;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),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}","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}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst float LinearEncodePowerApprox=2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\n#ifndef FROMLINEARSPACE\n\nresult.rgb=pow(result.rgb,vec3(LinearEncodePowerApprox));\n#endif\nresult.rgb*=cameraExposureLinear;\n#ifdef VIGNETTE\n\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\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,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\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}"};
  66060. 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(SHADOWCUBE{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(SHADOWCUBE{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(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D 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#ifdef NDOTL\nfloat ndl;\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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\n#ifdef NDOTL\nresult.ndl=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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D 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 SHADOWFLOAT\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 SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\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 SHADOWFLOAT\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\nreturn min(1.0,visibility+darkness);\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 SHADOWFLOAT\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.); \nreturn esm;\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 SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\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 SHADOWFLOAT\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\nreturn min(1.0,visibility+darkness);\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 SHADOWFLOAT\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\nreturn esm;\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#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\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#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,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 PBR\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#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#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{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(SHADOWCUBE{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(SHADOWCUBE{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#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif 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#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 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}","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  66061. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  66062. module.exports = BABYLON;
  66063. };