babylon.max.js 2.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413
  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. target[setCallback].apply(this);
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. };
  4778. }
  4779. function expandToProperty(callback, targetKey) {
  4780. return generateExpandMember(callback, targetKey);
  4781. }
  4782. BABYLON.expandToProperty = expandToProperty;
  4783. function serialize(sourceName) {
  4784. return generateSerializableMember(0, sourceName); // value member
  4785. }
  4786. BABYLON.serialize = serialize;
  4787. function serializeAsTexture(sourceName) {
  4788. return generateSerializableMember(1, sourceName); // texture member
  4789. }
  4790. BABYLON.serializeAsTexture = serializeAsTexture;
  4791. function serializeAsColor3(sourceName) {
  4792. return generateSerializableMember(2, sourceName); // color3 member
  4793. }
  4794. BABYLON.serializeAsColor3 = serializeAsColor3;
  4795. function serializeAsFresnelParameters(sourceName) {
  4796. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4797. }
  4798. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4799. function serializeAsVector2(sourceName) {
  4800. return generateSerializableMember(4, sourceName); // vector2 member
  4801. }
  4802. BABYLON.serializeAsVector2 = serializeAsVector2;
  4803. function serializeAsVector3(sourceName) {
  4804. return generateSerializableMember(5, sourceName); // vector3 member
  4805. }
  4806. BABYLON.serializeAsVector3 = serializeAsVector3;
  4807. function serializeAsMeshReference(sourceName) {
  4808. return generateSerializableMember(6, sourceName); // mesh reference member
  4809. }
  4810. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4811. function serializeAsColorCurves(sourceName) {
  4812. return generateSerializableMember(7, sourceName); // color curves
  4813. }
  4814. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4815. var SerializationHelper = (function () {
  4816. function SerializationHelper() {
  4817. }
  4818. SerializationHelper.Serialize = function (entity, serializationObject) {
  4819. if (!serializationObject) {
  4820. serializationObject = {};
  4821. }
  4822. // Tags
  4823. if (BABYLON.Tags) {
  4824. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4825. }
  4826. // Properties
  4827. for (var property in entity.__serializableMembers) {
  4828. var propertyDescriptor = entity.__serializableMembers[property];
  4829. var targetPropertyName = propertyDescriptor.sourceName || property;
  4830. var propertyType = propertyDescriptor.type;
  4831. var sourceProperty = entity[property];
  4832. if (sourceProperty !== undefined && sourceProperty !== null) {
  4833. switch (propertyType) {
  4834. case 0:
  4835. serializationObject[targetPropertyName] = sourceProperty;
  4836. break;
  4837. case 1:
  4838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4839. break;
  4840. case 2:
  4841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4842. break;
  4843. case 3:
  4844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4845. break;
  4846. case 4:
  4847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4848. break;
  4849. case 5:
  4850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4851. break;
  4852. case 6:
  4853. serializationObject[targetPropertyName] = sourceProperty.id;
  4854. break;
  4855. case 7:
  4856. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4857. break;
  4858. }
  4859. }
  4860. }
  4861. return serializationObject;
  4862. };
  4863. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4864. var destination = creationFunction();
  4865. // Tags
  4866. if (BABYLON.Tags) {
  4867. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4868. }
  4869. // Properties
  4870. for (var property in destination.__serializableMembers) {
  4871. var propertyDescriptor = destination.__serializableMembers[property];
  4872. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4873. var propertyType = propertyDescriptor.type;
  4874. if (sourceProperty !== undefined && sourceProperty !== null) {
  4875. switch (propertyType) {
  4876. case 0:
  4877. destination[property] = sourceProperty;
  4878. break;
  4879. case 1:
  4880. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4881. break;
  4882. case 2:
  4883. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4884. break;
  4885. case 3:
  4886. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4887. break;
  4888. case 4:
  4889. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4890. break;
  4891. case 5:
  4892. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4893. break;
  4894. case 6:
  4895. destination[property] = scene.getLastMeshByID(sourceProperty);
  4896. break;
  4897. case 7:
  4898. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4899. break;
  4900. }
  4901. }
  4902. }
  4903. return destination;
  4904. };
  4905. SerializationHelper.Clone = function (creationFunction, source) {
  4906. var destination = creationFunction();
  4907. // Tags
  4908. if (BABYLON.Tags) {
  4909. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4910. }
  4911. // Properties
  4912. for (var property in destination.__serializableMembers) {
  4913. var propertyDescriptor = destination.__serializableMembers[property];
  4914. var sourceProperty = source[property];
  4915. var propertyType = propertyDescriptor.type;
  4916. if (sourceProperty !== undefined && sourceProperty !== null) {
  4917. switch (propertyType) {
  4918. case 0: // Value
  4919. case 6:
  4920. destination[property] = sourceProperty;
  4921. break;
  4922. case 1: // Texture
  4923. case 2: // Color3
  4924. case 3: // FresnelParameters
  4925. case 4: // Vector2
  4926. case 5: // Vector3
  4927. case 7:
  4928. destination[property] = sourceProperty.clone();
  4929. break;
  4930. }
  4931. }
  4932. }
  4933. return destination;
  4934. };
  4935. return SerializationHelper;
  4936. }());
  4937. BABYLON.SerializationHelper = SerializationHelper;
  4938. })(BABYLON || (BABYLON = {}));
  4939. //# sourceMappingURL=babylon.decorators.js.map
  4940. var BABYLON;
  4941. (function (BABYLON) {
  4942. /**
  4943. * A class serves as a medium between the observable and its observers
  4944. */
  4945. var EventState = (function () {
  4946. /**
  4947. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4948. */
  4949. function EventState(mask, skipNextObservers) {
  4950. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4951. this.initalize(mask, skipNextObservers);
  4952. }
  4953. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4954. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4955. this.mask = mask;
  4956. this.skipNextObservers = skipNextObservers;
  4957. return this;
  4958. };
  4959. return EventState;
  4960. }());
  4961. BABYLON.EventState = EventState;
  4962. /**
  4963. * Represent an Observer registered to a given Observable object.
  4964. */
  4965. var Observer = (function () {
  4966. function Observer(callback, mask) {
  4967. this.callback = callback;
  4968. this.mask = mask;
  4969. }
  4970. return Observer;
  4971. }());
  4972. BABYLON.Observer = Observer;
  4973. /**
  4974. * The Observable class is a simple implementation of the Observable pattern.
  4975. * 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.
  4976. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4977. * 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).
  4978. * 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.
  4979. */
  4980. var Observable = (function () {
  4981. function Observable() {
  4982. this._observers = new Array();
  4983. this._eventState = new EventState(0);
  4984. }
  4985. /**
  4986. * Create a new Observer with the specified callback
  4987. * @param callback the callback that will be executed for that Observer
  4988. * @param mask the mask used to filter observers
  4989. * @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.
  4990. */
  4991. Observable.prototype.add = function (callback, mask, insertFirst) {
  4992. if (mask === void 0) { mask = -1; }
  4993. if (insertFirst === void 0) { insertFirst = false; }
  4994. if (!callback) {
  4995. return null;
  4996. }
  4997. var observer = new Observer(callback, mask);
  4998. if (insertFirst) {
  4999. this._observers.unshift(observer);
  5000. }
  5001. else {
  5002. this._observers.push(observer);
  5003. }
  5004. return observer;
  5005. };
  5006. /**
  5007. * Remove an Observer from the Observable object
  5008. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5009. */
  5010. Observable.prototype.remove = function (observer) {
  5011. var index = this._observers.indexOf(observer);
  5012. if (index !== -1) {
  5013. this._observers.splice(index, 1);
  5014. return true;
  5015. }
  5016. return false;
  5017. };
  5018. /**
  5019. * Remove a callback from the Observable object
  5020. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5021. */
  5022. Observable.prototype.removeCallback = function (callback) {
  5023. for (var index = 0; index < this._observers.length; index++) {
  5024. if (this._observers[index].callback === callback) {
  5025. this._observers.splice(index, 1);
  5026. return true;
  5027. }
  5028. }
  5029. return false;
  5030. };
  5031. /**
  5032. * Notify all Observers by calling their respective callback with the given data
  5033. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5034. * @param eventData
  5035. * @param mask
  5036. */
  5037. Observable.prototype.notifyObservers = function (eventData, mask) {
  5038. if (mask === void 0) { mask = -1; }
  5039. var state = this._eventState;
  5040. state.mask = mask;
  5041. state.skipNextObservers = false;
  5042. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5043. var obs = _a[_i];
  5044. if (obs.mask & mask) {
  5045. obs.callback(eventData, state);
  5046. }
  5047. if (state.skipNextObservers) {
  5048. return false;
  5049. }
  5050. }
  5051. return true;
  5052. };
  5053. /**
  5054. * return true is the Observable has at least one Observer registered
  5055. */
  5056. Observable.prototype.hasObservers = function () {
  5057. return this._observers.length > 0;
  5058. };
  5059. /**
  5060. * Clear the list of observers
  5061. */
  5062. Observable.prototype.clear = function () {
  5063. this._observers = new Array();
  5064. };
  5065. /**
  5066. * Clone the current observable
  5067. */
  5068. Observable.prototype.clone = function () {
  5069. var result = new Observable();
  5070. result._observers = this._observers.slice(0);
  5071. return result;
  5072. };
  5073. /**
  5074. * Does this observable handles observer registered with a given mask
  5075. * @param {number} trigger - the mask to be tested
  5076. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5077. **/
  5078. Observable.prototype.hasSpecificMask = function (mask) {
  5079. if (mask === void 0) { mask = -1; }
  5080. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5081. var obs = _a[_i];
  5082. if (obs.mask & mask && obs.mask === mask) {
  5083. return true;
  5084. }
  5085. }
  5086. return false;
  5087. };
  5088. return Observable;
  5089. }());
  5090. BABYLON.Observable = Observable;
  5091. })(BABYLON || (BABYLON = {}));
  5092. //# sourceMappingURL=babylon.observable.js.map
  5093. var BABYLON;
  5094. (function (BABYLON) {
  5095. var SmartArray = (function () {
  5096. function SmartArray(capacity) {
  5097. this.length = 0;
  5098. this._duplicateId = 0;
  5099. this.data = new Array(capacity);
  5100. this._id = SmartArray._GlobalId++;
  5101. }
  5102. SmartArray.prototype.push = function (value) {
  5103. this.data[this.length++] = value;
  5104. if (this.length > this.data.length) {
  5105. this.data.length *= 2;
  5106. }
  5107. if (!value.__smartArrayFlags) {
  5108. value.__smartArrayFlags = {};
  5109. }
  5110. value.__smartArrayFlags[this._id] = this._duplicateId;
  5111. };
  5112. SmartArray.prototype.forEach = function (func) {
  5113. for (var index = 0; index < this.length; index++) {
  5114. func(this.data[index]);
  5115. }
  5116. };
  5117. SmartArray.prototype.pushNoDuplicate = function (value) {
  5118. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5119. return false;
  5120. }
  5121. this.push(value);
  5122. return true;
  5123. };
  5124. SmartArray.prototype.sort = function (compareFn) {
  5125. this.data.sort(compareFn);
  5126. };
  5127. SmartArray.prototype.reset = function () {
  5128. this.length = 0;
  5129. this._duplicateId++;
  5130. };
  5131. SmartArray.prototype.dispose = function () {
  5132. this.reset();
  5133. this.data.length = 0;
  5134. };
  5135. SmartArray.prototype.concat = function (array) {
  5136. if (array.length === 0) {
  5137. return;
  5138. }
  5139. if (this.length + array.length > this.data.length) {
  5140. this.data.length = (this.length + array.length) * 2;
  5141. }
  5142. for (var index = 0; index < array.length; index++) {
  5143. this.data[this.length++] = (array.data || array)[index];
  5144. }
  5145. };
  5146. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5147. if (array.length === 0) {
  5148. return;
  5149. }
  5150. if (this.length + array.length > this.data.length) {
  5151. this.data.length = (this.length + array.length) * 2;
  5152. }
  5153. for (var index = 0; index < array.length; index++) {
  5154. var item = (array.data || array)[index];
  5155. this.pushNoDuplicate(item);
  5156. }
  5157. };
  5158. SmartArray.prototype.indexOf = function (value) {
  5159. var position = this.data.indexOf(value);
  5160. if (position >= this.length) {
  5161. return -1;
  5162. }
  5163. return position;
  5164. };
  5165. SmartArray.prototype.contains = function (value) {
  5166. return this.data.indexOf(value) !== -1;
  5167. };
  5168. return SmartArray;
  5169. }());
  5170. // Statics
  5171. SmartArray._GlobalId = 0;
  5172. BABYLON.SmartArray = SmartArray;
  5173. })(BABYLON || (BABYLON = {}));
  5174. //# sourceMappingURL=babylon.smartArray.js.map
  5175. var BABYLON;
  5176. (function (BABYLON) {
  5177. // Screenshots
  5178. var screenshotCanvas;
  5179. var cloneValue = function (source, destinationObject) {
  5180. if (!source)
  5181. return null;
  5182. if (source instanceof BABYLON.Mesh) {
  5183. return null;
  5184. }
  5185. if (source instanceof BABYLON.SubMesh) {
  5186. return source.clone(destinationObject);
  5187. }
  5188. else if (source.clone) {
  5189. return source.clone();
  5190. }
  5191. return null;
  5192. };
  5193. var Tools = (function () {
  5194. function Tools() {
  5195. }
  5196. ;
  5197. /**
  5198. * Interpolates between a and b via alpha
  5199. * @param a The lower value (returned when alpha = 0)
  5200. * @param b The upper value (returned when alpha = 1)
  5201. * @param alpha The interpolation-factor
  5202. * @return The mixed value
  5203. */
  5204. Tools.Mix = function (a, b, alpha) {
  5205. return a * (1 - alpha) + b * alpha;
  5206. };
  5207. Tools.Instantiate = function (className) {
  5208. var arr = className.split(".");
  5209. var fn = (window || this);
  5210. for (var i = 0, len = arr.length; i < len; i++) {
  5211. fn = fn[arr[i]];
  5212. }
  5213. if (typeof fn !== "function") {
  5214. return null;
  5215. }
  5216. return fn;
  5217. };
  5218. Tools.SetImmediate = function (action) {
  5219. if (window.setImmediate) {
  5220. window.setImmediate(action);
  5221. }
  5222. else {
  5223. setTimeout(action, 1);
  5224. }
  5225. };
  5226. Tools.IsExponentOfTwo = function (value) {
  5227. var count = 1;
  5228. do {
  5229. count *= 2;
  5230. } while (count < value);
  5231. return count === value;
  5232. };
  5233. /**
  5234. * Find the next highest power of two.
  5235. * @param x Number to start search from.
  5236. * @return Next highest power of two.
  5237. */
  5238. Tools.CeilingPOT = function (x) {
  5239. x--;
  5240. x |= x >> 1;
  5241. x |= x >> 2;
  5242. x |= x >> 4;
  5243. x |= x >> 8;
  5244. x |= x >> 16;
  5245. x++;
  5246. return x;
  5247. };
  5248. /**
  5249. * Find the next lowest power of two.
  5250. * @param x Number to start search from.
  5251. * @return Next lowest power of two.
  5252. */
  5253. Tools.FloorPOT = function (x) {
  5254. x = x | (x >> 1);
  5255. x = x | (x >> 2);
  5256. x = x | (x >> 4);
  5257. x = x | (x >> 8);
  5258. x = x | (x >> 16);
  5259. return x - (x >> 1);
  5260. };
  5261. /**
  5262. * Find the nearest power of two.
  5263. * @param x Number to start search from.
  5264. * @return Next nearest power of two.
  5265. */
  5266. Tools.NearestPOT = function (x) {
  5267. var c = Tools.CeilingPOT(x);
  5268. var f = Tools.FloorPOT(x);
  5269. return (c - x) > (x - f) ? f : c;
  5270. };
  5271. Tools.GetExponentOfTwo = function (value, max, mode) {
  5272. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5273. var pot;
  5274. switch (mode) {
  5275. case BABYLON.Engine.SCALEMODE_FLOOR:
  5276. pot = Tools.FloorPOT(value);
  5277. break;
  5278. case BABYLON.Engine.SCALEMODE_NEAREST:
  5279. pot = Tools.NearestPOT(value);
  5280. break;
  5281. case BABYLON.Engine.SCALEMODE_CEILING:
  5282. pot = Tools.CeilingPOT(value);
  5283. break;
  5284. }
  5285. return Math.min(pot, max);
  5286. };
  5287. Tools.GetFilename = function (path) {
  5288. var index = path.lastIndexOf("/");
  5289. if (index < 0)
  5290. return path;
  5291. return path.substring(index + 1);
  5292. };
  5293. Tools.GetDOMTextContent = function (element) {
  5294. var result = "";
  5295. var child = element.firstChild;
  5296. while (child) {
  5297. if (child.nodeType === 3) {
  5298. result += child.textContent;
  5299. }
  5300. child = child.nextSibling;
  5301. }
  5302. return result;
  5303. };
  5304. Tools.ToDegrees = function (angle) {
  5305. return angle * 180 / Math.PI;
  5306. };
  5307. Tools.ToRadians = function (angle) {
  5308. return angle * Math.PI / 180;
  5309. };
  5310. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5311. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5312. var output = "";
  5313. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5314. var i = 0;
  5315. var bytes = new Uint8Array(buffer);
  5316. while (i < bytes.length) {
  5317. chr1 = bytes[i++];
  5318. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5319. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5320. enc1 = chr1 >> 2;
  5321. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5322. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5323. enc4 = chr3 & 63;
  5324. if (isNaN(chr2)) {
  5325. enc3 = enc4 = 64;
  5326. }
  5327. else if (isNaN(chr3)) {
  5328. enc4 = 64;
  5329. }
  5330. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5331. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5332. }
  5333. return "data:image/png;base64," + output;
  5334. };
  5335. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5336. if (bias === void 0) { bias = null; }
  5337. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5338. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5339. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5340. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5341. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5342. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5343. }
  5344. if (bias) {
  5345. minimum.x -= minimum.x * bias.x + bias.y;
  5346. minimum.y -= minimum.y * bias.x + bias.y;
  5347. minimum.z -= minimum.z * bias.x + bias.y;
  5348. maximum.x += maximum.x * bias.x + bias.y;
  5349. maximum.y += maximum.y * bias.x + bias.y;
  5350. maximum.z += maximum.z * bias.x + bias.y;
  5351. }
  5352. return {
  5353. minimum: minimum,
  5354. maximum: maximum
  5355. };
  5356. };
  5357. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5358. if (bias === void 0) { bias = null; }
  5359. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5360. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5361. if (!stride) {
  5362. stride = 3;
  5363. }
  5364. for (var index = start; index < start + count; index++) {
  5365. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5366. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5367. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5368. }
  5369. if (bias) {
  5370. minimum.x -= minimum.x * bias.x + bias.y;
  5371. minimum.y -= minimum.y * bias.x + bias.y;
  5372. minimum.z -= minimum.z * bias.x + bias.y;
  5373. maximum.x += maximum.x * bias.x + bias.y;
  5374. maximum.y += maximum.y * bias.x + bias.y;
  5375. maximum.z += maximum.z * bias.x + bias.y;
  5376. }
  5377. return {
  5378. minimum: minimum,
  5379. maximum: maximum
  5380. };
  5381. };
  5382. Tools.Vector2ArrayFeeder = function (array) {
  5383. return function (index) {
  5384. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5385. var length = isFloatArray ? array.length / 2 : array.length;
  5386. if (index >= length) {
  5387. return null;
  5388. }
  5389. if (isFloatArray) {
  5390. var fa = array;
  5391. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5392. }
  5393. var a = array;
  5394. return a[index];
  5395. };
  5396. };
  5397. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5398. if (bias === void 0) { bias = null; }
  5399. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5400. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5401. var i = 0;
  5402. var cur = feeder(i++);
  5403. while (cur) {
  5404. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5405. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5406. cur = feeder(i++);
  5407. }
  5408. if (bias) {
  5409. minimum.x -= minimum.x * bias.x + bias.y;
  5410. minimum.y -= minimum.y * bias.x + bias.y;
  5411. maximum.x += maximum.x * bias.x + bias.y;
  5412. maximum.y += maximum.y * bias.x + bias.y;
  5413. }
  5414. return {
  5415. minimum: minimum,
  5416. maximum: maximum
  5417. };
  5418. };
  5419. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5420. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5421. return undefined;
  5422. return Array.isArray(obj) ? obj : [obj];
  5423. };
  5424. // Misc.
  5425. Tools.GetPointerPrefix = function () {
  5426. var eventPrefix = "pointer";
  5427. // Check if pointer events are supported
  5428. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5429. eventPrefix = "mouse";
  5430. }
  5431. return eventPrefix;
  5432. };
  5433. /**
  5434. * @param func - the function to be called
  5435. * @param requester - the object that will request the next frame. Falls back to window.
  5436. */
  5437. Tools.QueueNewFrame = function (func, requester) {
  5438. if (requester === void 0) { requester = window; }
  5439. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5440. /*if(requester.isPresenting) {
  5441. return;
  5442. } else*/ if (requester.requestAnimationFrame)
  5443. requester.requestAnimationFrame(func);
  5444. else if (requester.msRequestAnimationFrame)
  5445. requester.msRequestAnimationFrame(func);
  5446. else if (requester.webkitRequestAnimationFrame)
  5447. requester.webkitRequestAnimationFrame(func);
  5448. else if (requester.mozRequestAnimationFrame)
  5449. requester.mozRequestAnimationFrame(func);
  5450. else if (requester.oRequestAnimationFrame)
  5451. requester.oRequestAnimationFrame(func);
  5452. else {
  5453. window.setTimeout(func, 16);
  5454. }
  5455. };
  5456. Tools.RequestFullscreen = function (element) {
  5457. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5458. if (!requestFunction)
  5459. return;
  5460. requestFunction.call(element);
  5461. };
  5462. Tools.ExitFullscreen = function () {
  5463. if (document.exitFullscreen) {
  5464. document.exitFullscreen();
  5465. }
  5466. else if (document.mozCancelFullScreen) {
  5467. document.mozCancelFullScreen();
  5468. }
  5469. else if (document.webkitCancelFullScreen) {
  5470. document.webkitCancelFullScreen();
  5471. }
  5472. else if (document.msCancelFullScreen) {
  5473. document.msCancelFullScreen();
  5474. }
  5475. };
  5476. Tools.SetCorsBehavior = function (url, img) {
  5477. if (Tools.CorsBehavior) {
  5478. switch (typeof (Tools.CorsBehavior)) {
  5479. case "function":
  5480. var result = Tools.CorsBehavior(url);
  5481. if (result) {
  5482. img.crossOrigin = result;
  5483. }
  5484. break;
  5485. case "string":
  5486. default:
  5487. img.crossOrigin = Tools.CorsBehavior;
  5488. break;
  5489. }
  5490. }
  5491. };
  5492. // External files
  5493. Tools.CleanUrl = function (url) {
  5494. url = url.replace(/#/mg, "%23");
  5495. return url;
  5496. };
  5497. Tools.LoadImage = function (url, onload, onerror, database) {
  5498. if (url instanceof ArrayBuffer) {
  5499. url = Tools.EncodeArrayBufferTobase64(url);
  5500. }
  5501. url = Tools.CleanUrl(url);
  5502. var img = new Image();
  5503. if (url.substr(0, 5) !== "data:") {
  5504. Tools.SetCorsBehavior(url, img);
  5505. }
  5506. img.onload = function () {
  5507. onload(img);
  5508. };
  5509. img.onerror = function (err) {
  5510. Tools.Error("Error while trying to load image: " + url);
  5511. if (Tools.UseFallbackTexture) {
  5512. img.src = Tools.fallbackTexture;
  5513. onload(img);
  5514. }
  5515. else {
  5516. onerror();
  5517. }
  5518. };
  5519. var noIndexedDB = function () {
  5520. img.src = url;
  5521. };
  5522. var loadFromIndexedDB = function () {
  5523. database.loadImageFromDB(url, img);
  5524. };
  5525. //ANY database to do!
  5526. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5527. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5528. }
  5529. else {
  5530. if (url.indexOf("file:") !== 0) {
  5531. noIndexedDB();
  5532. }
  5533. else {
  5534. var textureName = url.substring(5).toLowerCase();
  5535. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5536. try {
  5537. var blobURL;
  5538. try {
  5539. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5540. }
  5541. catch (ex) {
  5542. // Chrome doesn't support oneTimeOnly parameter
  5543. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5544. }
  5545. img.src = blobURL;
  5546. }
  5547. catch (e) {
  5548. img.src = null;
  5549. }
  5550. }
  5551. else {
  5552. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5553. img.src = Tools.fallbackTexture;
  5554. }
  5555. }
  5556. }
  5557. return img;
  5558. };
  5559. //ANY
  5560. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5561. url = Tools.CleanUrl(url);
  5562. var noIndexedDB = function () {
  5563. var request = new XMLHttpRequest();
  5564. var loadUrl = Tools.BaseUrl + url;
  5565. request.open('GET', loadUrl, true);
  5566. if (useArrayBuffer) {
  5567. request.responseType = "arraybuffer";
  5568. }
  5569. request.onprogress = progressCallBack;
  5570. request.onreadystatechange = function () {
  5571. // In case of undefined state in some browsers.
  5572. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5573. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5574. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5575. callback(!useArrayBuffer ? request.responseText : request.response);
  5576. }
  5577. else {
  5578. if (onError) {
  5579. onError(request);
  5580. }
  5581. else {
  5582. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5583. }
  5584. }
  5585. }
  5586. };
  5587. request.send(null);
  5588. };
  5589. var loadFromIndexedDB = function () {
  5590. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5591. };
  5592. if (url.indexOf("file:") !== -1) {
  5593. var fileName = url.substring(5).toLowerCase();
  5594. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5595. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5596. }
  5597. else {
  5598. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5599. }
  5600. }
  5601. else {
  5602. // Caching all files
  5603. if (database && database.enableSceneOffline) {
  5604. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5605. }
  5606. else {
  5607. noIndexedDB();
  5608. }
  5609. }
  5610. };
  5611. /**
  5612. * Load a script (identified by an url). When the url returns, the
  5613. * content of this file is added into a new script element, attached to the DOM (body element)
  5614. */
  5615. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5616. var head = document.getElementsByTagName('head')[0];
  5617. var script = document.createElement('script');
  5618. script.type = 'text/javascript';
  5619. script.src = scriptUrl;
  5620. var self = this;
  5621. script.onload = function () {
  5622. if (onSuccess) {
  5623. onSuccess();
  5624. }
  5625. };
  5626. script.onerror = function () {
  5627. if (onError) {
  5628. onError();
  5629. }
  5630. };
  5631. head.appendChild(script);
  5632. };
  5633. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5634. var reader = new FileReader();
  5635. reader.onload = function (e) {
  5636. //target doesn't have result from ts 1.3
  5637. callback(e.target['result']);
  5638. };
  5639. reader.onprogress = progressCallback;
  5640. reader.readAsDataURL(fileToLoad);
  5641. };
  5642. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5643. var reader = new FileReader();
  5644. reader.onerror = function (e) {
  5645. Tools.Log("Error while reading file: " + fileToLoad.name);
  5646. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5647. };
  5648. reader.onload = function (e) {
  5649. //target doesn't have result from ts 1.3
  5650. callback(e.target['result']);
  5651. };
  5652. reader.onprogress = progressCallBack;
  5653. if (!useArrayBuffer) {
  5654. // Asynchronous read
  5655. reader.readAsText(fileToLoad);
  5656. }
  5657. else {
  5658. reader.readAsArrayBuffer(fileToLoad);
  5659. }
  5660. };
  5661. //returns a downloadable url to a file content.
  5662. Tools.FileAsURL = function (content) {
  5663. var fileBlob = new Blob([content]);
  5664. var url = window.URL || window.webkitURL;
  5665. var link = url.createObjectURL(fileBlob);
  5666. return link;
  5667. };
  5668. // Misc.
  5669. Tools.Format = function (value, decimals) {
  5670. if (decimals === void 0) { decimals = 2; }
  5671. return value.toFixed(decimals);
  5672. };
  5673. Tools.CheckExtends = function (v, min, max) {
  5674. if (v.x < min.x)
  5675. min.x = v.x;
  5676. if (v.y < min.y)
  5677. min.y = v.y;
  5678. if (v.z < min.z)
  5679. min.z = v.z;
  5680. if (v.x > max.x)
  5681. max.x = v.x;
  5682. if (v.y > max.y)
  5683. max.y = v.y;
  5684. if (v.z > max.z)
  5685. max.z = v.z;
  5686. };
  5687. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5688. for (var prop in source) {
  5689. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5690. continue;
  5691. }
  5692. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5693. continue;
  5694. }
  5695. var sourceValue = source[prop];
  5696. var typeOfSourceValue = typeof sourceValue;
  5697. if (typeOfSourceValue === "function") {
  5698. continue;
  5699. }
  5700. if (typeOfSourceValue === "object") {
  5701. if (sourceValue instanceof Array) {
  5702. destination[prop] = [];
  5703. if (sourceValue.length > 0) {
  5704. if (typeof sourceValue[0] == "object") {
  5705. for (var index = 0; index < sourceValue.length; index++) {
  5706. var clonedValue = cloneValue(sourceValue[index], destination);
  5707. if (destination[prop].indexOf(clonedValue) === -1) {
  5708. destination[prop].push(clonedValue);
  5709. }
  5710. }
  5711. }
  5712. else {
  5713. destination[prop] = sourceValue.slice(0);
  5714. }
  5715. }
  5716. }
  5717. else {
  5718. destination[prop] = cloneValue(sourceValue, destination);
  5719. }
  5720. }
  5721. else {
  5722. destination[prop] = sourceValue;
  5723. }
  5724. }
  5725. };
  5726. Tools.IsEmpty = function (obj) {
  5727. for (var i in obj) {
  5728. return false;
  5729. }
  5730. return true;
  5731. };
  5732. Tools.RegisterTopRootEvents = function (events) {
  5733. for (var index = 0; index < events.length; index++) {
  5734. var event = events[index];
  5735. window.addEventListener(event.name, event.handler, false);
  5736. try {
  5737. if (window.parent) {
  5738. window.parent.addEventListener(event.name, event.handler, false);
  5739. }
  5740. }
  5741. catch (e) {
  5742. // Silently fails...
  5743. }
  5744. }
  5745. };
  5746. Tools.UnregisterTopRootEvents = function (events) {
  5747. for (var index = 0; index < events.length; index++) {
  5748. var event = events[index];
  5749. window.removeEventListener(event.name, event.handler);
  5750. try {
  5751. if (window.parent) {
  5752. window.parent.removeEventListener(event.name, event.handler);
  5753. }
  5754. }
  5755. catch (e) {
  5756. // Silently fails...
  5757. }
  5758. }
  5759. };
  5760. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5761. if (mimeType === void 0) { mimeType = "image/png"; }
  5762. // Read the contents of the framebuffer
  5763. var numberOfChannelsByLine = width * 4;
  5764. var halfHeight = height / 2;
  5765. //Reading datas from WebGL
  5766. var data = engine.readPixels(0, 0, width, height);
  5767. //To flip image on Y axis.
  5768. for (var i = 0; i < halfHeight; i++) {
  5769. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5770. var currentCell = j + i * numberOfChannelsByLine;
  5771. var targetLine = height - i - 1;
  5772. var targetCell = j + targetLine * numberOfChannelsByLine;
  5773. var temp = data[currentCell];
  5774. data[currentCell] = data[targetCell];
  5775. data[targetCell] = temp;
  5776. }
  5777. }
  5778. // Create a 2D canvas to store the result
  5779. if (!screenshotCanvas) {
  5780. screenshotCanvas = document.createElement('canvas');
  5781. }
  5782. screenshotCanvas.width = width;
  5783. screenshotCanvas.height = height;
  5784. var context = screenshotCanvas.getContext('2d');
  5785. // Copy the pixels to a 2D canvas
  5786. var imageData = context.createImageData(width, height);
  5787. var castData = (imageData.data);
  5788. castData.set(data);
  5789. context.putImageData(imageData, 0, 0);
  5790. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5791. };
  5792. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5793. if (mimeType === void 0) { mimeType = "image/png"; }
  5794. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5795. if (successCallback) {
  5796. successCallback(base64Image);
  5797. }
  5798. else {
  5799. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5800. if (("download" in document.createElement("a"))) {
  5801. var a = window.document.createElement("a");
  5802. a.href = base64Image;
  5803. var date = new Date();
  5804. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5805. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5806. window.document.body.appendChild(a);
  5807. a.addEventListener("click", function () {
  5808. a.parentElement.removeChild(a);
  5809. });
  5810. a.click();
  5811. //Or opening a new tab with the image if it is not possible to automatically start download.
  5812. }
  5813. else {
  5814. var newWindow = window.open("");
  5815. var img = newWindow.document.createElement("img");
  5816. img.src = base64Image;
  5817. newWindow.document.body.appendChild(img);
  5818. }
  5819. }
  5820. };
  5821. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5822. if (mimeType === void 0) { mimeType = "image/png"; }
  5823. var width;
  5824. var height;
  5825. // If a precision value is specified
  5826. if (size.precision) {
  5827. width = Math.round(engine.getRenderWidth() * size.precision);
  5828. height = Math.round(width / engine.getAspectRatio(camera));
  5829. }
  5830. else if (size.width && size.height) {
  5831. width = size.width;
  5832. height = size.height;
  5833. }
  5834. else if (size.width && !size.height) {
  5835. width = size.width;
  5836. height = Math.round(width / engine.getAspectRatio(camera));
  5837. }
  5838. else if (size.height && !size.width) {
  5839. height = size.height;
  5840. width = Math.round(height * engine.getAspectRatio(camera));
  5841. }
  5842. else if (!isNaN(size)) {
  5843. height = size;
  5844. width = size;
  5845. }
  5846. else {
  5847. Tools.Error("Invalid 'size' parameter !");
  5848. return;
  5849. }
  5850. if (!screenshotCanvas) {
  5851. screenshotCanvas = document.createElement('canvas');
  5852. }
  5853. screenshotCanvas.width = width;
  5854. screenshotCanvas.height = height;
  5855. var renderContext = screenshotCanvas.getContext("2d");
  5856. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5857. var newWidth = width;
  5858. var newHeight = newWidth / ratio;
  5859. if (newHeight > height) {
  5860. newHeight = height;
  5861. newWidth = newHeight * ratio;
  5862. }
  5863. var offsetX = Math.max(0, width - newWidth) / 2;
  5864. var offsetY = Math.max(0, height - newHeight) / 2;
  5865. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5866. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5867. };
  5868. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5869. if (mimeType === void 0) { mimeType = "image/png"; }
  5870. if (samples === void 0) { samples = 1; }
  5871. var width;
  5872. var height;
  5873. //If a precision value is specified
  5874. if (size.precision) {
  5875. width = Math.round(engine.getRenderWidth() * size.precision);
  5876. height = Math.round(width / engine.getAspectRatio(camera));
  5877. size = { width: width, height: height };
  5878. }
  5879. else if (size.width && size.height) {
  5880. width = size.width;
  5881. height = size.height;
  5882. }
  5883. else if (size.width && !size.height) {
  5884. width = size.width;
  5885. height = Math.round(width / engine.getAspectRatio(camera));
  5886. size = { width: width, height: height };
  5887. }
  5888. else if (size.height && !size.width) {
  5889. height = size.height;
  5890. width = Math.round(height * engine.getAspectRatio(camera));
  5891. size = { width: width, height: height };
  5892. }
  5893. else if (!isNaN(size)) {
  5894. height = size;
  5895. width = size;
  5896. }
  5897. else {
  5898. Tools.Error("Invalid 'size' parameter !");
  5899. return;
  5900. }
  5901. var scene = camera.getScene();
  5902. var previousCamera = null;
  5903. if (scene.activeCamera !== camera) {
  5904. previousCamera = scene.activeCamera;
  5905. scene.activeCamera = camera;
  5906. }
  5907. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5908. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5909. texture.renderList = scene.meshes;
  5910. texture.samples = samples;
  5911. texture.onAfterRenderObservable.add(function () {
  5912. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5913. });
  5914. scene.incrementRenderId();
  5915. scene.resetCachedMaterial();
  5916. texture.render(true);
  5917. texture.dispose();
  5918. if (previousCamera) {
  5919. scene.activeCamera = previousCamera;
  5920. }
  5921. camera.getProjectionMatrix(true); // Force cache refresh;
  5922. };
  5923. // XHR response validator for local file scenario
  5924. Tools.ValidateXHRData = function (xhr, dataType) {
  5925. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5926. if (dataType === void 0) { dataType = 7; }
  5927. try {
  5928. if (dataType & 1) {
  5929. if (xhr.responseText && xhr.responseText.length > 0) {
  5930. return true;
  5931. }
  5932. else if (dataType === 1) {
  5933. return false;
  5934. }
  5935. }
  5936. if (dataType & 2) {
  5937. // Check header width and height since there is no "TGA" magic number
  5938. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5939. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5940. return true;
  5941. }
  5942. else if (dataType === 2) {
  5943. return false;
  5944. }
  5945. }
  5946. if (dataType & 4) {
  5947. // Check for the "DDS" magic number
  5948. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5949. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5950. return true;
  5951. }
  5952. else {
  5953. return false;
  5954. }
  5955. }
  5956. }
  5957. catch (e) {
  5958. // Global protection
  5959. }
  5960. return false;
  5961. };
  5962. /**
  5963. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5964. * Be aware Math.random() could cause collisions, but:
  5965. * "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"
  5966. */
  5967. Tools.RandomId = function () {
  5968. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5969. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5970. return v.toString(16);
  5971. });
  5972. };
  5973. Object.defineProperty(Tools, "NoneLogLevel", {
  5974. get: function () {
  5975. return Tools._NoneLogLevel;
  5976. },
  5977. enumerable: true,
  5978. configurable: true
  5979. });
  5980. Object.defineProperty(Tools, "MessageLogLevel", {
  5981. get: function () {
  5982. return Tools._MessageLogLevel;
  5983. },
  5984. enumerable: true,
  5985. configurable: true
  5986. });
  5987. Object.defineProperty(Tools, "WarningLogLevel", {
  5988. get: function () {
  5989. return Tools._WarningLogLevel;
  5990. },
  5991. enumerable: true,
  5992. configurable: true
  5993. });
  5994. Object.defineProperty(Tools, "ErrorLogLevel", {
  5995. get: function () {
  5996. return Tools._ErrorLogLevel;
  5997. },
  5998. enumerable: true,
  5999. configurable: true
  6000. });
  6001. Object.defineProperty(Tools, "AllLogLevel", {
  6002. get: function () {
  6003. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6004. },
  6005. enumerable: true,
  6006. configurable: true
  6007. });
  6008. Tools._AddLogEntry = function (entry) {
  6009. Tools._LogCache = entry + Tools._LogCache;
  6010. if (Tools.OnNewCacheEntry) {
  6011. Tools.OnNewCacheEntry(entry);
  6012. }
  6013. };
  6014. Tools._FormatMessage = function (message) {
  6015. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6016. var date = new Date();
  6017. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6018. };
  6019. Tools._LogDisabled = function (message) {
  6020. // nothing to do
  6021. };
  6022. Tools._LogEnabled = function (message) {
  6023. var formattedMessage = Tools._FormatMessage(message);
  6024. console.log("BJS - " + formattedMessage);
  6025. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6026. Tools._AddLogEntry(entry);
  6027. };
  6028. Tools._WarnDisabled = function (message) {
  6029. // nothing to do
  6030. };
  6031. Tools._WarnEnabled = function (message) {
  6032. var formattedMessage = Tools._FormatMessage(message);
  6033. console.warn("BJS - " + formattedMessage);
  6034. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6035. Tools._AddLogEntry(entry);
  6036. };
  6037. Tools._ErrorDisabled = function (message) {
  6038. // nothing to do
  6039. };
  6040. Tools._ErrorEnabled = function (message) {
  6041. Tools.errorsCount++;
  6042. var formattedMessage = Tools._FormatMessage(message);
  6043. console.error("BJS - " + formattedMessage);
  6044. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6045. Tools._AddLogEntry(entry);
  6046. };
  6047. Object.defineProperty(Tools, "LogCache", {
  6048. get: function () {
  6049. return Tools._LogCache;
  6050. },
  6051. enumerable: true,
  6052. configurable: true
  6053. });
  6054. Tools.ClearLogCache = function () {
  6055. Tools._LogCache = "";
  6056. Tools.errorsCount = 0;
  6057. };
  6058. Object.defineProperty(Tools, "LogLevels", {
  6059. set: function (level) {
  6060. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6061. Tools.Log = Tools._LogEnabled;
  6062. }
  6063. else {
  6064. Tools.Log = Tools._LogDisabled;
  6065. }
  6066. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6067. Tools.Warn = Tools._WarnEnabled;
  6068. }
  6069. else {
  6070. Tools.Warn = Tools._WarnDisabled;
  6071. }
  6072. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6073. Tools.Error = Tools._ErrorEnabled;
  6074. }
  6075. else {
  6076. Tools.Error = Tools._ErrorDisabled;
  6077. }
  6078. },
  6079. enumerable: true,
  6080. configurable: true
  6081. });
  6082. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6083. get: function () {
  6084. return Tools._PerformanceNoneLogLevel;
  6085. },
  6086. enumerable: true,
  6087. configurable: true
  6088. });
  6089. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6090. get: function () {
  6091. return Tools._PerformanceUserMarkLogLevel;
  6092. },
  6093. enumerable: true,
  6094. configurable: true
  6095. });
  6096. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6097. get: function () {
  6098. return Tools._PerformanceConsoleLogLevel;
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6104. set: function (level) {
  6105. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6106. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6107. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6108. return;
  6109. }
  6110. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6111. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6112. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6113. return;
  6114. }
  6115. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6116. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6122. };
  6123. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6124. };
  6125. Tools._StartUserMark = function (counterName, condition) {
  6126. if (condition === void 0) { condition = true; }
  6127. if (!condition || !Tools._performance.mark) {
  6128. return;
  6129. }
  6130. Tools._performance.mark(counterName + "-Begin");
  6131. };
  6132. Tools._EndUserMark = function (counterName, condition) {
  6133. if (condition === void 0) { condition = true; }
  6134. if (!condition || !Tools._performance.mark) {
  6135. return;
  6136. }
  6137. Tools._performance.mark(counterName + "-End");
  6138. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6139. };
  6140. Tools._StartPerformanceConsole = function (counterName, condition) {
  6141. if (condition === void 0) { condition = true; }
  6142. if (!condition) {
  6143. return;
  6144. }
  6145. Tools._StartUserMark(counterName, condition);
  6146. if (console.time) {
  6147. console.time(counterName);
  6148. }
  6149. };
  6150. Tools._EndPerformanceConsole = function (counterName, condition) {
  6151. if (condition === void 0) { condition = true; }
  6152. if (!condition) {
  6153. return;
  6154. }
  6155. Tools._EndUserMark(counterName, condition);
  6156. if (console.time) {
  6157. console.timeEnd(counterName);
  6158. }
  6159. };
  6160. Object.defineProperty(Tools, "Now", {
  6161. get: function () {
  6162. if (window.performance && window.performance.now) {
  6163. return window.performance.now();
  6164. }
  6165. return new Date().getTime();
  6166. },
  6167. enumerable: true,
  6168. configurable: true
  6169. });
  6170. /**
  6171. * This method will return the name of the class used to create the instance of the given object.
  6172. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6173. * @param object the object to get the class name from
  6174. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6175. */
  6176. Tools.getClassName = function (object, isType) {
  6177. if (isType === void 0) { isType = false; }
  6178. var name = null;
  6179. if (!isType && object.getClassName) {
  6180. name = object.getClassName();
  6181. }
  6182. else {
  6183. if (object instanceof Object) {
  6184. var classObj = isType ? object : Object.getPrototypeOf(object);
  6185. name = classObj.constructor["__bjsclassName__"];
  6186. }
  6187. if (!name) {
  6188. name = typeof object;
  6189. }
  6190. }
  6191. return name;
  6192. };
  6193. Tools.first = function (array, predicate) {
  6194. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6195. var el = array_1[_i];
  6196. if (predicate(el)) {
  6197. return el;
  6198. }
  6199. }
  6200. };
  6201. /**
  6202. * This method will return the name of the full name of the class, including its owning module (if any).
  6203. * 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).
  6204. * @param object the object to get the class name from
  6205. * @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.
  6206. */
  6207. Tools.getFullClassName = function (object, isType) {
  6208. if (isType === void 0) { isType = false; }
  6209. var className = null;
  6210. var moduleName = null;
  6211. if (!isType && object.getClassName) {
  6212. className = object.getClassName();
  6213. }
  6214. else {
  6215. if (object instanceof Object) {
  6216. var classObj = isType ? object : Object.getPrototypeOf(object);
  6217. className = classObj.constructor["__bjsclassName__"];
  6218. moduleName = classObj.constructor["__bjsmoduleName__"];
  6219. }
  6220. if (!className) {
  6221. className = typeof object;
  6222. }
  6223. }
  6224. if (!className) {
  6225. return null;
  6226. }
  6227. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6228. };
  6229. /**
  6230. * 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.
  6231. * @param array
  6232. */
  6233. Tools.arrayOrStringFeeder = function (array) {
  6234. return function (index) {
  6235. if (index >= array.length) {
  6236. return null;
  6237. }
  6238. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6239. if (val && val.getHashCode) {
  6240. val = val.getHashCode();
  6241. }
  6242. if (typeof val === "string") {
  6243. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6244. }
  6245. return val;
  6246. };
  6247. };
  6248. /**
  6249. * Compute the hashCode of a stream of number
  6250. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6251. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6252. * @return the hash code computed
  6253. */
  6254. Tools.hashCodeFromStream = function (feeder) {
  6255. // Based from here: http://stackoverflow.com/a/7616484/802124
  6256. var hash = 0;
  6257. var index = 0;
  6258. var chr = feeder(index++);
  6259. while (chr != null) {
  6260. hash = ((hash << 5) - hash) + chr;
  6261. hash |= 0; // Convert to 32bit integer
  6262. chr = feeder(index++);
  6263. }
  6264. return hash;
  6265. };
  6266. return Tools;
  6267. }());
  6268. Tools.BaseUrl = "";
  6269. Tools.CorsBehavior = "anonymous";
  6270. Tools.UseFallbackTexture = true;
  6271. // Used in case of a texture loading problem
  6272. 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";
  6273. // Logs
  6274. Tools._NoneLogLevel = 0;
  6275. Tools._MessageLogLevel = 1;
  6276. Tools._WarningLogLevel = 2;
  6277. Tools._ErrorLogLevel = 4;
  6278. Tools._LogCache = "";
  6279. Tools.errorsCount = 0;
  6280. Tools.Log = Tools._LogEnabled;
  6281. Tools.Warn = Tools._WarnEnabled;
  6282. Tools.Error = Tools._ErrorEnabled;
  6283. // Performances
  6284. Tools._PerformanceNoneLogLevel = 0;
  6285. Tools._PerformanceUserMarkLogLevel = 1;
  6286. Tools._PerformanceConsoleLogLevel = 2;
  6287. Tools._performance = window.performance;
  6288. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6289. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6290. BABYLON.Tools = Tools;
  6291. /**
  6292. * This class is used to track a performance counter which is number based.
  6293. * The user has access to many properties which give statistics of different nature
  6294. *
  6295. * The implementer can track two kinds of Performance Counter: time and count
  6296. * 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.
  6297. * 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.
  6298. */
  6299. var PerfCounter = (function () {
  6300. function PerfCounter() {
  6301. this._startMonitoringTime = 0;
  6302. this._min = 0;
  6303. this._max = 0;
  6304. this._average = 0;
  6305. this._lastSecAverage = 0;
  6306. this._current = 0;
  6307. this._totalValueCount = 0;
  6308. this._totalAccumulated = 0;
  6309. this._lastSecAccumulated = 0;
  6310. this._lastSecTime = 0;
  6311. this._lastSecValueCount = 0;
  6312. }
  6313. Object.defineProperty(PerfCounter.prototype, "min", {
  6314. /**
  6315. * Returns the smallest value ever
  6316. */
  6317. get: function () {
  6318. return this._min;
  6319. },
  6320. enumerable: true,
  6321. configurable: true
  6322. });
  6323. Object.defineProperty(PerfCounter.prototype, "max", {
  6324. /**
  6325. * Returns the biggest value ever
  6326. */
  6327. get: function () {
  6328. return this._max;
  6329. },
  6330. enumerable: true,
  6331. configurable: true
  6332. });
  6333. Object.defineProperty(PerfCounter.prototype, "average", {
  6334. /**
  6335. * Returns the average value since the performance counter is running
  6336. */
  6337. get: function () {
  6338. return this._average;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6344. /**
  6345. * Returns the average value of the last second the counter was monitored
  6346. */
  6347. get: function () {
  6348. return this._lastSecAverage;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "current", {
  6354. /**
  6355. * Returns the current value
  6356. */
  6357. get: function () {
  6358. return this._current;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "total", {
  6364. get: function () {
  6365. return this._totalAccumulated;
  6366. },
  6367. enumerable: true,
  6368. configurable: true
  6369. });
  6370. /**
  6371. * Call this method to start monitoring a new frame.
  6372. * 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.
  6373. */
  6374. PerfCounter.prototype.fetchNewFrame = function () {
  6375. this._totalValueCount++;
  6376. this._current = 0;
  6377. this._lastSecValueCount++;
  6378. };
  6379. /**
  6380. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6381. * @param newCount the count value to add to the monitored count
  6382. * @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.
  6383. */
  6384. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6385. if (!PerfCounter.Enabled) {
  6386. return;
  6387. }
  6388. this._current += newCount;
  6389. if (fetchResult) {
  6390. this._fetchResult();
  6391. }
  6392. };
  6393. /**
  6394. * Start monitoring this performance counter
  6395. */
  6396. PerfCounter.prototype.beginMonitoring = function () {
  6397. if (!PerfCounter.Enabled) {
  6398. return;
  6399. }
  6400. this._startMonitoringTime = Tools.Now;
  6401. };
  6402. /**
  6403. * Compute the time lapsed since the previous beginMonitoring() call.
  6404. * @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
  6405. */
  6406. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6407. if (newFrame === void 0) { newFrame = true; }
  6408. if (!PerfCounter.Enabled) {
  6409. return;
  6410. }
  6411. if (newFrame) {
  6412. this.fetchNewFrame();
  6413. }
  6414. var currentTime = Tools.Now;
  6415. this._current = currentTime - this._startMonitoringTime;
  6416. if (newFrame) {
  6417. this._fetchResult();
  6418. }
  6419. };
  6420. PerfCounter.prototype._fetchResult = function () {
  6421. this._totalAccumulated += this._current;
  6422. this._lastSecAccumulated += this._current;
  6423. // Min/Max update
  6424. this._min = Math.min(this._min, this._current);
  6425. this._max = Math.max(this._max, this._current);
  6426. this._average = this._totalAccumulated / this._totalValueCount;
  6427. // Reset last sec?
  6428. var now = Tools.Now;
  6429. if ((now - this._lastSecTime) > 1000) {
  6430. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6431. this._lastSecTime = now;
  6432. this._lastSecAccumulated = 0;
  6433. this._lastSecValueCount = 0;
  6434. }
  6435. };
  6436. return PerfCounter;
  6437. }());
  6438. PerfCounter.Enabled = true;
  6439. BABYLON.PerfCounter = PerfCounter;
  6440. /**
  6441. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6442. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6443. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6444. * @param name The name of the class, case should be preserved
  6445. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6446. */
  6447. function className(name, module) {
  6448. return function (target) {
  6449. target["__bjsclassName__"] = name;
  6450. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6451. };
  6452. }
  6453. BABYLON.className = className;
  6454. /**
  6455. * An implementation of a loop for asynchronous functions.
  6456. */
  6457. var AsyncLoop = (function () {
  6458. /**
  6459. * Constroctor.
  6460. * @param iterations the number of iterations.
  6461. * @param _fn the function to run each iteration
  6462. * @param _successCallback the callback that will be called upon succesful execution
  6463. * @param offset starting offset.
  6464. */
  6465. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6466. if (offset === void 0) { offset = 0; }
  6467. this.iterations = iterations;
  6468. this._fn = _fn;
  6469. this._successCallback = _successCallback;
  6470. this.index = offset - 1;
  6471. this._done = false;
  6472. }
  6473. /**
  6474. * Execute the next iteration. Must be called after the last iteration was finished.
  6475. */
  6476. AsyncLoop.prototype.executeNext = function () {
  6477. if (!this._done) {
  6478. if (this.index + 1 < this.iterations) {
  6479. ++this.index;
  6480. this._fn(this);
  6481. }
  6482. else {
  6483. this.breakLoop();
  6484. }
  6485. }
  6486. };
  6487. /**
  6488. * Break the loop and run the success callback.
  6489. */
  6490. AsyncLoop.prototype.breakLoop = function () {
  6491. this._done = true;
  6492. this._successCallback();
  6493. };
  6494. /**
  6495. * Helper function
  6496. */
  6497. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6498. if (offset === void 0) { offset = 0; }
  6499. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6500. loop.executeNext();
  6501. return loop;
  6502. };
  6503. /**
  6504. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6505. * @param iterations total number of iterations
  6506. * @param syncedIterations number of synchronous iterations in each async iteration.
  6507. * @param fn the function to call each iteration.
  6508. * @param callback a success call back that will be called when iterating stops.
  6509. * @param breakFunction a break condition (optional)
  6510. * @param timeout timeout settings for the setTimeout function. default - 0.
  6511. * @constructor
  6512. */
  6513. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6514. if (timeout === void 0) { timeout = 0; }
  6515. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6516. if (breakFunction && breakFunction())
  6517. loop.breakLoop();
  6518. else {
  6519. setTimeout(function () {
  6520. for (var i = 0; i < syncedIterations; ++i) {
  6521. var iteration = (loop.index * syncedIterations) + i;
  6522. if (iteration >= iterations)
  6523. break;
  6524. fn(iteration);
  6525. if (breakFunction && breakFunction()) {
  6526. loop.breakLoop();
  6527. break;
  6528. }
  6529. }
  6530. loop.executeNext();
  6531. }, timeout);
  6532. }
  6533. }, callback);
  6534. };
  6535. return AsyncLoop;
  6536. }());
  6537. BABYLON.AsyncLoop = AsyncLoop;
  6538. })(BABYLON || (BABYLON = {}));
  6539. //# sourceMappingURL=babylon.tools.js.map
  6540. var BABYLON;
  6541. (function (BABYLON) {
  6542. var Internals;
  6543. (function (Internals) {
  6544. var _AlphaState = (function () {
  6545. /**
  6546. * Initializes the state.
  6547. */
  6548. function _AlphaState() {
  6549. this._isAlphaBlendDirty = false;
  6550. this._isBlendFunctionParametersDirty = false;
  6551. this._isBlendEquationParametersDirty = false;
  6552. this._isBlendConstantsDirty = false;
  6553. this._alphaBlend = false;
  6554. this._blendFunctionParameters = new Array(4);
  6555. this._blendEquationParameters = new Array(2);
  6556. this._blendConstants = new Array(4);
  6557. this.reset();
  6558. }
  6559. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6560. get: function () {
  6561. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6567. get: function () {
  6568. return this._alphaBlend;
  6569. },
  6570. set: function (value) {
  6571. if (this._alphaBlend === value) {
  6572. return;
  6573. }
  6574. this._alphaBlend = value;
  6575. this._isAlphaBlendDirty = true;
  6576. },
  6577. enumerable: true,
  6578. configurable: true
  6579. });
  6580. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6581. if (this._blendConstants[0] === r &&
  6582. this._blendConstants[1] === g &&
  6583. this._blendConstants[2] === b &&
  6584. this._blendConstants[3] === a) {
  6585. return;
  6586. }
  6587. this._blendConstants[0] = r;
  6588. this._blendConstants[1] = g;
  6589. this._blendConstants[2] = b;
  6590. this._blendConstants[3] = a;
  6591. this._isBlendConstantsDirty = true;
  6592. };
  6593. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6594. if (this._blendFunctionParameters[0] === value0 &&
  6595. this._blendFunctionParameters[1] === value1 &&
  6596. this._blendFunctionParameters[2] === value2 &&
  6597. this._blendFunctionParameters[3] === value3) {
  6598. return;
  6599. }
  6600. this._blendFunctionParameters[0] = value0;
  6601. this._blendFunctionParameters[1] = value1;
  6602. this._blendFunctionParameters[2] = value2;
  6603. this._blendFunctionParameters[3] = value3;
  6604. this._isBlendFunctionParametersDirty = true;
  6605. };
  6606. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6607. if (this._blendEquationParameters[0] === rgb &&
  6608. this._blendEquationParameters[1] === alpha) {
  6609. return;
  6610. }
  6611. this._blendEquationParameters[0] = rgb;
  6612. this._blendEquationParameters[1] = alpha;
  6613. this._isBlendEquationParametersDirty = true;
  6614. };
  6615. _AlphaState.prototype.reset = function () {
  6616. this._alphaBlend = false;
  6617. this._blendFunctionParameters[0] = null;
  6618. this._blendFunctionParameters[1] = null;
  6619. this._blendFunctionParameters[2] = null;
  6620. this._blendFunctionParameters[3] = null;
  6621. this._blendEquationParameters[0] = null;
  6622. this._blendEquationParameters[1] = null;
  6623. this._blendConstants[0] = null;
  6624. this._blendConstants[1] = null;
  6625. this._blendConstants[2] = null;
  6626. this._blendConstants[3] = null;
  6627. this._isAlphaBlendDirty = true;
  6628. this._isBlendFunctionParametersDirty = false;
  6629. this._isBlendEquationParametersDirty = false;
  6630. this._isBlendConstantsDirty = false;
  6631. };
  6632. _AlphaState.prototype.apply = function (gl) {
  6633. if (!this.isDirty) {
  6634. return;
  6635. }
  6636. // Alpha blend
  6637. if (this._isAlphaBlendDirty) {
  6638. if (this._alphaBlend) {
  6639. gl.enable(gl.BLEND);
  6640. }
  6641. else {
  6642. gl.disable(gl.BLEND);
  6643. }
  6644. this._isAlphaBlendDirty = false;
  6645. }
  6646. // Alpha function
  6647. if (this._isBlendFunctionParametersDirty) {
  6648. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6649. this._isBlendFunctionParametersDirty = false;
  6650. }
  6651. // Alpha equation
  6652. if (this._isBlendEquationParametersDirty) {
  6653. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6654. this._isBlendEquationParametersDirty = false;
  6655. }
  6656. // Constants
  6657. if (this._isBlendConstantsDirty) {
  6658. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6659. this._isBlendConstantsDirty = false;
  6660. }
  6661. };
  6662. return _AlphaState;
  6663. }());
  6664. Internals._AlphaState = _AlphaState;
  6665. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6666. })(BABYLON || (BABYLON = {}));
  6667. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6668. var BABYLON;
  6669. (function (BABYLON) {
  6670. var Internals;
  6671. (function (Internals) {
  6672. var _DepthCullingState = (function () {
  6673. /**
  6674. * Initializes the state.
  6675. */
  6676. function _DepthCullingState() {
  6677. this._isDepthTestDirty = false;
  6678. this._isDepthMaskDirty = false;
  6679. this._isDepthFuncDirty = false;
  6680. this._isCullFaceDirty = false;
  6681. this._isCullDirty = false;
  6682. this._isZOffsetDirty = false;
  6683. this.reset();
  6684. }
  6685. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6686. get: function () {
  6687. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6688. },
  6689. enumerable: true,
  6690. configurable: true
  6691. });
  6692. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6693. get: function () {
  6694. return this._zOffset;
  6695. },
  6696. set: function (value) {
  6697. if (this._zOffset === value) {
  6698. return;
  6699. }
  6700. this._zOffset = value;
  6701. this._isZOffsetDirty = true;
  6702. },
  6703. enumerable: true,
  6704. configurable: true
  6705. });
  6706. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6707. get: function () {
  6708. return this._cullFace;
  6709. },
  6710. set: function (value) {
  6711. if (this._cullFace === value) {
  6712. return;
  6713. }
  6714. this._cullFace = value;
  6715. this._isCullFaceDirty = true;
  6716. },
  6717. enumerable: true,
  6718. configurable: true
  6719. });
  6720. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6721. get: function () {
  6722. return this._cull;
  6723. },
  6724. set: function (value) {
  6725. if (this._cull === value) {
  6726. return;
  6727. }
  6728. this._cull = value;
  6729. this._isCullDirty = true;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6735. get: function () {
  6736. return this._depthFunc;
  6737. },
  6738. set: function (value) {
  6739. if (this._depthFunc === value) {
  6740. return;
  6741. }
  6742. this._depthFunc = value;
  6743. this._isDepthFuncDirty = true;
  6744. },
  6745. enumerable: true,
  6746. configurable: true
  6747. });
  6748. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6749. get: function () {
  6750. return this._depthMask;
  6751. },
  6752. set: function (value) {
  6753. if (this._depthMask === value) {
  6754. return;
  6755. }
  6756. this._depthMask = value;
  6757. this._isDepthMaskDirty = true;
  6758. },
  6759. enumerable: true,
  6760. configurable: true
  6761. });
  6762. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6763. get: function () {
  6764. return this._depthTest;
  6765. },
  6766. set: function (value) {
  6767. if (this._depthTest === value) {
  6768. return;
  6769. }
  6770. this._depthTest = value;
  6771. this._isDepthTestDirty = true;
  6772. },
  6773. enumerable: true,
  6774. configurable: true
  6775. });
  6776. _DepthCullingState.prototype.reset = function () {
  6777. this._depthMask = true;
  6778. this._depthTest = true;
  6779. this._depthFunc = null;
  6780. this._cullFace = null;
  6781. this._cull = null;
  6782. this._zOffset = 0;
  6783. this._isDepthTestDirty = true;
  6784. this._isDepthMaskDirty = true;
  6785. this._isDepthFuncDirty = false;
  6786. this._isCullFaceDirty = false;
  6787. this._isCullDirty = false;
  6788. this._isZOffsetDirty = false;
  6789. };
  6790. _DepthCullingState.prototype.apply = function (gl) {
  6791. if (!this.isDirty) {
  6792. return;
  6793. }
  6794. // Cull
  6795. if (this._isCullDirty) {
  6796. if (this.cull) {
  6797. gl.enable(gl.CULL_FACE);
  6798. }
  6799. else {
  6800. gl.disable(gl.CULL_FACE);
  6801. }
  6802. this._isCullDirty = false;
  6803. }
  6804. // Cull face
  6805. if (this._isCullFaceDirty) {
  6806. gl.cullFace(this.cullFace);
  6807. this._isCullFaceDirty = false;
  6808. }
  6809. // Depth mask
  6810. if (this._isDepthMaskDirty) {
  6811. gl.depthMask(this.depthMask);
  6812. this._isDepthMaskDirty = false;
  6813. }
  6814. // Depth test
  6815. if (this._isDepthTestDirty) {
  6816. if (this.depthTest) {
  6817. gl.enable(gl.DEPTH_TEST);
  6818. }
  6819. else {
  6820. gl.disable(gl.DEPTH_TEST);
  6821. }
  6822. this._isDepthTestDirty = false;
  6823. }
  6824. // Depth func
  6825. if (this._isDepthFuncDirty) {
  6826. gl.depthFunc(this.depthFunc);
  6827. this._isDepthFuncDirty = false;
  6828. }
  6829. // zOffset
  6830. if (this._isZOffsetDirty) {
  6831. if (this.zOffset) {
  6832. gl.enable(gl.POLYGON_OFFSET_FILL);
  6833. gl.polygonOffset(this.zOffset, 0);
  6834. }
  6835. else {
  6836. gl.disable(gl.POLYGON_OFFSET_FILL);
  6837. }
  6838. this._isZOffsetDirty = false;
  6839. }
  6840. };
  6841. return _DepthCullingState;
  6842. }());
  6843. Internals._DepthCullingState = _DepthCullingState;
  6844. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6845. })(BABYLON || (BABYLON = {}));
  6846. //# sourceMappingURL=babylon.depthCullingState.js.map
  6847. var BABYLON;
  6848. (function (BABYLON) {
  6849. var Internals;
  6850. (function (Internals) {
  6851. var _StencilState = (function () {
  6852. function _StencilState() {
  6853. this._isStencilTestDirty = false;
  6854. this._isStencilMaskDirty = false;
  6855. this._isStencilFuncDirty = false;
  6856. this._isStencilOpDirty = false;
  6857. this.reset();
  6858. }
  6859. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6860. get: function () {
  6861. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6862. },
  6863. enumerable: true,
  6864. configurable: true
  6865. });
  6866. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6867. get: function () {
  6868. return this._stencilFunc;
  6869. },
  6870. set: function (value) {
  6871. if (this._stencilFunc === value) {
  6872. return;
  6873. }
  6874. this._stencilFunc = value;
  6875. this._isStencilFuncDirty = true;
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6881. get: function () {
  6882. return this._stencilFuncRef;
  6883. },
  6884. set: function (value) {
  6885. if (this._stencilFuncRef === value) {
  6886. return;
  6887. }
  6888. this._stencilFuncRef = value;
  6889. this._isStencilFuncDirty = true;
  6890. },
  6891. enumerable: true,
  6892. configurable: true
  6893. });
  6894. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6895. get: function () {
  6896. return this._stencilFuncMask;
  6897. },
  6898. set: function (value) {
  6899. if (this._stencilFuncMask === value) {
  6900. return;
  6901. }
  6902. this._stencilFuncMask = value;
  6903. this._isStencilFuncDirty = true;
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6909. get: function () {
  6910. return this._stencilOpStencilFail;
  6911. },
  6912. set: function (value) {
  6913. if (this._stencilOpStencilFail === value) {
  6914. return;
  6915. }
  6916. this._stencilOpStencilFail = value;
  6917. this._isStencilOpDirty = true;
  6918. },
  6919. enumerable: true,
  6920. configurable: true
  6921. });
  6922. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6923. get: function () {
  6924. return this._stencilOpDepthFail;
  6925. },
  6926. set: function (value) {
  6927. if (this._stencilOpDepthFail === value) {
  6928. return;
  6929. }
  6930. this._stencilOpDepthFail = value;
  6931. this._isStencilOpDirty = true;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6937. get: function () {
  6938. return this._stencilOpStencilDepthPass;
  6939. },
  6940. set: function (value) {
  6941. if (this._stencilOpStencilDepthPass === value) {
  6942. return;
  6943. }
  6944. this._stencilOpStencilDepthPass = value;
  6945. this._isStencilOpDirty = true;
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6951. get: function () {
  6952. return this._stencilMask;
  6953. },
  6954. set: function (value) {
  6955. if (this._stencilMask === value) {
  6956. return;
  6957. }
  6958. this._stencilMask = value;
  6959. this._isStencilMaskDirty = true;
  6960. },
  6961. enumerable: true,
  6962. configurable: true
  6963. });
  6964. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6965. get: function () {
  6966. return this._stencilTest;
  6967. },
  6968. set: function (value) {
  6969. if (this._stencilTest === value) {
  6970. return;
  6971. }
  6972. this._stencilTest = value;
  6973. this._isStencilTestDirty = true;
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. _StencilState.prototype.reset = function () {
  6979. this._stencilTest = false;
  6980. this._stencilMask = 0xFF;
  6981. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6982. this._stencilFuncRef = 1;
  6983. this._stencilFuncMask = 0xFF;
  6984. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6985. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6986. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6987. this._isStencilTestDirty = true;
  6988. this._isStencilMaskDirty = true;
  6989. this._isStencilFuncDirty = true;
  6990. this._isStencilOpDirty = true;
  6991. };
  6992. _StencilState.prototype.apply = function (gl) {
  6993. if (!this.isDirty) {
  6994. return;
  6995. }
  6996. // Stencil test
  6997. if (this._isStencilTestDirty) {
  6998. if (this.stencilTest) {
  6999. gl.enable(gl.STENCIL_TEST);
  7000. }
  7001. else {
  7002. gl.disable(gl.STENCIL_TEST);
  7003. }
  7004. this._isStencilTestDirty = false;
  7005. }
  7006. // Stencil mask
  7007. if (this._isStencilMaskDirty) {
  7008. gl.stencilMask(this.stencilMask);
  7009. this._isStencilMaskDirty = false;
  7010. }
  7011. // Stencil func
  7012. if (this._isStencilFuncDirty) {
  7013. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7014. this._isStencilFuncDirty = false;
  7015. }
  7016. // Stencil op
  7017. if (this._isStencilOpDirty) {
  7018. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7019. this._isStencilOpDirty = false;
  7020. }
  7021. };
  7022. return _StencilState;
  7023. }());
  7024. Internals._StencilState = _StencilState;
  7025. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7026. })(BABYLON || (BABYLON = {}));
  7027. //# sourceMappingURL=babylon.stencilState.js.map
  7028. var BABYLON;
  7029. (function (BABYLON) {
  7030. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7031. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7032. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7033. gl.compileShader(shader);
  7034. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7035. throw new Error(gl.getShaderInfoLog(shader));
  7036. }
  7037. return shader;
  7038. };
  7039. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7040. var magFilter = gl.NEAREST;
  7041. var minFilter = gl.NEAREST;
  7042. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7043. magFilter = gl.LINEAR;
  7044. if (generateMipMaps) {
  7045. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7046. }
  7047. else {
  7048. minFilter = gl.LINEAR;
  7049. }
  7050. }
  7051. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7052. magFilter = gl.LINEAR;
  7053. if (generateMipMaps) {
  7054. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7055. }
  7056. else {
  7057. minFilter = gl.LINEAR;
  7058. }
  7059. }
  7060. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7061. magFilter = gl.NEAREST;
  7062. if (generateMipMaps) {
  7063. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7064. }
  7065. else {
  7066. minFilter = gl.NEAREST;
  7067. }
  7068. }
  7069. return {
  7070. min: minFilter,
  7071. mag: magFilter
  7072. };
  7073. };
  7074. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7076. var engine = scene.getEngine();
  7077. if (!engine) {
  7078. return;
  7079. }
  7080. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7081. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7082. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7083. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7084. texture._baseWidth = width;
  7085. texture._baseHeight = height;
  7086. texture._width = potWidth;
  7087. texture._height = potHeight;
  7088. texture.isReady = true;
  7089. processFunction(potWidth, potHeight);
  7090. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7093. if (!noMipmap && !isCompressed) {
  7094. gl.generateMipmap(gl.TEXTURE_2D);
  7095. }
  7096. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7097. engine.resetTextureCache();
  7098. scene._removePendingData(texture);
  7099. texture.onLoadedCallbacks.forEach(function (callback) {
  7100. callback();
  7101. });
  7102. texture.onLoadedCallbacks = [];
  7103. };
  7104. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7105. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7106. var img;
  7107. var onload = function () {
  7108. loadedImages[index] = img;
  7109. loadedImages._internalCount++;
  7110. scene._removePendingData(img);
  7111. if (loadedImages._internalCount === 6) {
  7112. onfinish(loadedImages);
  7113. }
  7114. };
  7115. var onerror = function () {
  7116. scene._removePendingData(img);
  7117. if (onErrorCallBack) {
  7118. onErrorCallBack();
  7119. }
  7120. };
  7121. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7122. scene._addPendingData(img);
  7123. };
  7124. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7125. if (onError === void 0) { onError = null; }
  7126. var loadedImages = [];
  7127. loadedImages._internalCount = 0;
  7128. for (var index = 0; index < 6; index++) {
  7129. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7130. }
  7131. };
  7132. var InstancingAttributeInfo = (function () {
  7133. function InstancingAttributeInfo() {
  7134. }
  7135. return InstancingAttributeInfo;
  7136. }());
  7137. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7138. var EngineCapabilities = (function () {
  7139. function EngineCapabilities() {
  7140. }
  7141. return EngineCapabilities;
  7142. }());
  7143. BABYLON.EngineCapabilities = EngineCapabilities;
  7144. /**
  7145. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7146. */
  7147. var Engine = (function () {
  7148. /**
  7149. * @constructor
  7150. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7151. * @param {boolean} [antialias] - enable antialias
  7152. * @param options - further options to be sent to the getContext function
  7153. */
  7154. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7155. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7156. var _this = this;
  7157. // Public members
  7158. this.isFullscreen = false;
  7159. this.isPointerLock = false;
  7160. this.cullBackFaces = true;
  7161. this.renderEvenInBackground = true;
  7162. this.preventCacheWipeBetweenFrames = false;
  7163. // To enable/disable IDB support and avoid XHR on .manifest
  7164. this.enableOfflineSupport = BABYLON.Database;
  7165. this.scenes = new Array();
  7166. // Observables
  7167. /**
  7168. * Observable event triggered each time the rendering canvas is resized
  7169. */
  7170. this.onResizeObservable = new BABYLON.Observable();
  7171. /**
  7172. * Observable event triggered each time the canvas lost focus
  7173. */
  7174. this.onCanvasBlurObservable = new BABYLON.Observable();
  7175. this._windowIsBackground = false;
  7176. this._webGLVersion = 1.0;
  7177. this._badOS = false;
  7178. this._drawCalls = new BABYLON.PerfCounter();
  7179. this._renderingQueueLaunched = false;
  7180. this._activeRenderLoops = [];
  7181. // FPS
  7182. this.fpsRange = 60;
  7183. this.previousFramesDuration = [];
  7184. this.fps = 60;
  7185. this.deltaTime = 0;
  7186. // States
  7187. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7188. this._stencilState = new BABYLON.Internals._StencilState();
  7189. this._alphaState = new BABYLON.Internals._AlphaState();
  7190. this._alphaMode = Engine.ALPHA_DISABLE;
  7191. // Cache
  7192. this._loadedTexturesCache = new Array();
  7193. this._maxTextureChannels = 16;
  7194. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7195. this._compiledEffects = {};
  7196. this._vertexAttribArraysEnabled = [];
  7197. this._uintIndicesCurrentlySet = false;
  7198. this._currentBoundBuffer = new Array();
  7199. this._currentBufferPointers = [];
  7200. this._currentInstanceLocations = new Array();
  7201. this._currentInstanceBuffers = new Array();
  7202. this._vaoRecordInProgress = false;
  7203. this._mustWipeVertexAttributes = false;
  7204. // Hardware supported Compressed Textures
  7205. this._texturesSupported = new Array();
  7206. this._onVRFullScreenTriggered = function () {
  7207. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7208. //get the old size before we change
  7209. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7210. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7211. //get the width and height, change the render size
  7212. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7213. var width, height;
  7214. _this.setHardwareScalingLevel(1);
  7215. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7216. }
  7217. else {
  7218. //When the specs are implemented, need to uncomment this.
  7219. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7220. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7221. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7222. _this._vrDisplayEnabled = undefined;
  7223. }
  7224. };
  7225. this._renderingCanvas = canvas;
  7226. Engine.Instances.push(this);
  7227. options = options || {};
  7228. if (antialias != null) {
  7229. options.antialias = antialias;
  7230. }
  7231. if (options.preserveDrawingBuffer === undefined) {
  7232. options.preserveDrawingBuffer = false;
  7233. }
  7234. if (options.audioEngine === undefined) {
  7235. options.audioEngine = true;
  7236. }
  7237. if (options.stencil === undefined) {
  7238. options.stencil = true;
  7239. }
  7240. // GL
  7241. if (!options.disableWebGL2Support) {
  7242. try {
  7243. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7244. if (this._gl) {
  7245. this._webGLVersion = 2.0;
  7246. }
  7247. }
  7248. catch (e) {
  7249. // Do nothing
  7250. }
  7251. }
  7252. if (!this._gl) {
  7253. if (!canvas) {
  7254. throw new Error("The provided canvas is null or undefined.");
  7255. }
  7256. try {
  7257. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7258. }
  7259. catch (e) {
  7260. throw new Error("WebGL not supported");
  7261. }
  7262. }
  7263. if (!this._gl) {
  7264. throw new Error("WebGL not supported");
  7265. }
  7266. this._onBlur = function () {
  7267. _this._windowIsBackground = true;
  7268. };
  7269. this._onFocus = function () {
  7270. _this._windowIsBackground = false;
  7271. };
  7272. this._onCanvasBlur = function () {
  7273. _this.onCanvasBlurObservable.notifyObservers(_this);
  7274. };
  7275. window.addEventListener("blur", this._onBlur);
  7276. window.addEventListener("focus", this._onFocus);
  7277. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7278. // Viewport
  7279. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7280. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7281. this.resize();
  7282. // Caps
  7283. this._isStencilEnable = options.stencil;
  7284. this._caps = new EngineCapabilities();
  7285. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7286. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7287. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7288. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7289. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7290. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7291. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7292. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7293. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7294. // Infos
  7295. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7296. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7297. if (rendererInfo != null) {
  7298. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7299. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7300. }
  7301. if (!this._glVendor) {
  7302. this._glVendor = "Unknown vendor";
  7303. }
  7304. if (!this._glRenderer) {
  7305. this._glRenderer = "Unknown renderer";
  7306. }
  7307. // Extensions
  7308. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7309. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7310. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7311. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7312. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7313. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7314. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7315. 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');
  7316. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7317. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7318. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7319. this._caps.highPrecisionShaderSupported = true;
  7320. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7321. // Checks if some of the format renders first to allow the use of webgl inspector.
  7322. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7323. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7324. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7325. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7326. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7327. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7328. if (this._webGLVersion > 1) {
  7329. Engine.HALF_FLOAT_OES = 0x140B;
  7330. }
  7331. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7332. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7333. // Vertex array object
  7334. if (this._webGLVersion > 1) {
  7335. this._caps.vertexArrayObject = true;
  7336. }
  7337. else {
  7338. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7339. if (vertexArrayObjectExtension != null) {
  7340. this._caps.vertexArrayObject = true;
  7341. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7342. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7343. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7344. }
  7345. else {
  7346. this._caps.vertexArrayObject = false;
  7347. }
  7348. }
  7349. // Instances count
  7350. if (this._webGLVersion > 1) {
  7351. this._caps.instancedArrays = true;
  7352. }
  7353. else {
  7354. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7355. if (instanceExtension != null) {
  7356. this._caps.instancedArrays = true;
  7357. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7358. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7359. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7360. }
  7361. else {
  7362. this._caps.instancedArrays = false;
  7363. }
  7364. }
  7365. // Intelligently add supported compressed formats in order to check for.
  7366. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7367. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7368. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7369. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7370. if (this._caps.astc)
  7371. this.texturesSupported.push('-astc.ktx');
  7372. if (this._caps.s3tc)
  7373. this.texturesSupported.push('-dxt.ktx');
  7374. if (this._caps.pvrtc)
  7375. this.texturesSupported.push('-pvrtc.ktx');
  7376. if (this._caps.etc2)
  7377. this.texturesSupported.push('-etc2.ktx');
  7378. if (this._caps.etc1)
  7379. this.texturesSupported.push('-etc1.ktx');
  7380. if (this._gl.getShaderPrecisionFormat) {
  7381. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7382. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7383. }
  7384. // Depth buffer
  7385. this.setDepthBuffer(true);
  7386. this.setDepthFunctionToLessOrEqual();
  7387. this.setDepthWrite(true);
  7388. // Fullscreen
  7389. this._onFullscreenChange = function () {
  7390. if (document.fullscreen !== undefined) {
  7391. _this.isFullscreen = document.fullscreen;
  7392. }
  7393. else if (document.mozFullScreen !== undefined) {
  7394. _this.isFullscreen = document.mozFullScreen;
  7395. }
  7396. else if (document.webkitIsFullScreen !== undefined) {
  7397. _this.isFullscreen = document.webkitIsFullScreen;
  7398. }
  7399. else if (document.msIsFullScreen !== undefined) {
  7400. _this.isFullscreen = document.msIsFullScreen;
  7401. }
  7402. // Pointer lock
  7403. if (_this.isFullscreen && _this._pointerLockRequested) {
  7404. canvas.requestPointerLock = canvas.requestPointerLock ||
  7405. canvas.msRequestPointerLock ||
  7406. canvas.mozRequestPointerLock ||
  7407. canvas.webkitRequestPointerLock;
  7408. if (canvas.requestPointerLock) {
  7409. canvas.requestPointerLock();
  7410. }
  7411. }
  7412. };
  7413. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7414. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7415. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7416. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7417. // Pointer lock
  7418. this._onPointerLockChange = function () {
  7419. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7420. document.webkitPointerLockElement === canvas ||
  7421. document.msPointerLockElement === canvas ||
  7422. document.pointerLockElement === canvas);
  7423. };
  7424. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7425. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7426. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7427. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7428. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7429. Engine.audioEngine = new BABYLON.AudioEngine();
  7430. }
  7431. //Load WebVR Devices
  7432. if (options.autoEnableWebVR) {
  7433. this.initWebVR();
  7434. }
  7435. //Detect if we are running on a faulty buggy OS.
  7436. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7437. //ua sniffing is the tool of the devil.
  7438. this._badOS = regexp.test(navigator.userAgent);
  7439. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7440. }
  7441. Object.defineProperty(Engine, "LastCreatedEngine", {
  7442. get: function () {
  7443. if (Engine.Instances.length === 0) {
  7444. return null;
  7445. }
  7446. return Engine.Instances[Engine.Instances.length - 1];
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(Engine, "LastCreatedScene", {
  7452. get: function () {
  7453. var lastCreatedEngine = Engine.LastCreatedEngine;
  7454. if (!lastCreatedEngine) {
  7455. return null;
  7456. }
  7457. if (lastCreatedEngine.scenes.length === 0) {
  7458. return null;
  7459. }
  7460. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. /**
  7466. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7467. */
  7468. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7469. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7470. var engine = Engine.Instances[engineIndex];
  7471. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7472. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7473. }
  7474. }
  7475. };
  7476. Object.defineProperty(Engine, "NEVER", {
  7477. get: function () {
  7478. return Engine._NEVER;
  7479. },
  7480. enumerable: true,
  7481. configurable: true
  7482. });
  7483. Object.defineProperty(Engine, "ALWAYS", {
  7484. get: function () {
  7485. return Engine._ALWAYS;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(Engine, "LESS", {
  7491. get: function () {
  7492. return Engine._LESS;
  7493. },
  7494. enumerable: true,
  7495. configurable: true
  7496. });
  7497. Object.defineProperty(Engine, "EQUAL", {
  7498. get: function () {
  7499. return Engine._EQUAL;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(Engine, "LEQUAL", {
  7505. get: function () {
  7506. return Engine._LEQUAL;
  7507. },
  7508. enumerable: true,
  7509. configurable: true
  7510. });
  7511. Object.defineProperty(Engine, "GREATER", {
  7512. get: function () {
  7513. return Engine._GREATER;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(Engine, "GEQUAL", {
  7519. get: function () {
  7520. return Engine._GEQUAL;
  7521. },
  7522. enumerable: true,
  7523. configurable: true
  7524. });
  7525. Object.defineProperty(Engine, "NOTEQUAL", {
  7526. get: function () {
  7527. return Engine._NOTEQUAL;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(Engine, "KEEP", {
  7533. get: function () {
  7534. return Engine._KEEP;
  7535. },
  7536. enumerable: true,
  7537. configurable: true
  7538. });
  7539. Object.defineProperty(Engine, "REPLACE", {
  7540. get: function () {
  7541. return Engine._REPLACE;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(Engine, "INCR", {
  7547. get: function () {
  7548. return Engine._INCR;
  7549. },
  7550. enumerable: true,
  7551. configurable: true
  7552. });
  7553. Object.defineProperty(Engine, "DECR", {
  7554. get: function () {
  7555. return Engine._DECR;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(Engine, "INVERT", {
  7561. get: function () {
  7562. return Engine._INVERT;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(Engine, "INCR_WRAP", {
  7568. get: function () {
  7569. return Engine._INCR_WRAP;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Engine, "DECR_WRAP", {
  7575. get: function () {
  7576. return Engine._DECR_WRAP;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7582. get: function () {
  7583. return Engine._ALPHA_DISABLE;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7589. get: function () {
  7590. return Engine._ALPHA_ONEONE;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(Engine, "ALPHA_ADD", {
  7596. get: function () {
  7597. return Engine._ALPHA_ADD;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7603. get: function () {
  7604. return Engine._ALPHA_COMBINE;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7610. get: function () {
  7611. return Engine._ALPHA_SUBTRACT;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7617. get: function () {
  7618. return Engine._ALPHA_MULTIPLY;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7624. get: function () {
  7625. return Engine._ALPHA_MAXIMIZED;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7631. get: function () {
  7632. return Engine._ALPHA_PREMULTIPLIED;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7638. get: function () {
  7639. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7645. get: function () {
  7646. return Engine._ALPHA_INTERPOLATE;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7652. get: function () {
  7653. return Engine._ALPHA_SCREENMODE;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7659. get: function () {
  7660. return Engine._DELAYLOADSTATE_NONE;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7666. get: function () {
  7667. return Engine._DELAYLOADSTATE_LOADED;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7673. get: function () {
  7674. return Engine._DELAYLOADSTATE_LOADING;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7680. get: function () {
  7681. return Engine._DELAYLOADSTATE_NOTLOADED;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7687. get: function () {
  7688. return Engine._TEXTUREFORMAT_ALPHA;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7694. get: function () {
  7695. return Engine._TEXTUREFORMAT_LUMINANCE;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7701. get: function () {
  7702. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7708. get: function () {
  7709. return Engine._TEXTUREFORMAT_RGB;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7715. get: function () {
  7716. return Engine._TEXTUREFORMAT_RGBA;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7722. get: function () {
  7723. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7729. get: function () {
  7730. return Engine._TEXTURETYPE_FLOAT;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7736. get: function () {
  7737. return Engine._TEXTURETYPE_HALF_FLOAT;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7743. get: function () {
  7744. return Engine._SCALEMODE_FLOOR;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7750. get: function () {
  7751. return Engine._SCALEMODE_NEAREST;
  7752. },
  7753. enumerable: true,
  7754. configurable: true
  7755. });
  7756. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7757. get: function () {
  7758. return Engine._SCALEMODE_CEILING;
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. Object.defineProperty(Engine, "Version", {
  7764. get: function () {
  7765. return "3.0-beta";
  7766. },
  7767. enumerable: true,
  7768. configurable: true
  7769. });
  7770. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7771. get: function () {
  7772. return this._texturesSupported;
  7773. },
  7774. enumerable: true,
  7775. configurable: true
  7776. });
  7777. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7778. get: function () {
  7779. return this._textureFormatInUse;
  7780. },
  7781. enumerable: true,
  7782. configurable: true
  7783. });
  7784. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7785. // Empty texture
  7786. get: function () {
  7787. if (!this._emptyTexture) {
  7788. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7789. }
  7790. return this._emptyTexture;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7796. get: function () {
  7797. if (!this._emptyCubeTexture) {
  7798. var faceData = new Uint8Array(4);
  7799. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7800. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7801. }
  7802. return this._emptyCubeTexture;
  7803. },
  7804. enumerable: true,
  7805. configurable: true
  7806. });
  7807. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7808. get: function () {
  7809. return this._webGLVersion;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7815. /**
  7816. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7817. */
  7818. get: function () {
  7819. return this._isStencilEnable;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Engine.prototype._prepareWorkingCanvas = function () {
  7825. if (this._workingCanvas) {
  7826. return;
  7827. }
  7828. this._workingCanvas = document.createElement("canvas");
  7829. this._workingContext = this._workingCanvas.getContext("2d");
  7830. };
  7831. Engine.prototype.resetTextureCache = function () {
  7832. for (var index = 0; index < this._maxTextureChannels; index++) {
  7833. this._activeTexturesCache[index] = null;
  7834. }
  7835. };
  7836. Engine.prototype.getGlInfo = function () {
  7837. return {
  7838. vendor: this._glVendor,
  7839. renderer: this._glRenderer,
  7840. version: this._glVersion
  7841. };
  7842. };
  7843. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7844. if (useScreen === void 0) { useScreen = false; }
  7845. var viewport = camera.viewport;
  7846. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7847. };
  7848. Engine.prototype.getRenderWidth = function (useScreen) {
  7849. if (useScreen === void 0) { useScreen = false; }
  7850. if (!useScreen && this._currentRenderTarget) {
  7851. return this._currentRenderTarget._width;
  7852. }
  7853. return this._renderingCanvas.width;
  7854. };
  7855. Engine.prototype.getRenderHeight = function (useScreen) {
  7856. if (useScreen === void 0) { useScreen = false; }
  7857. if (!useScreen && this._currentRenderTarget) {
  7858. return this._currentRenderTarget._height;
  7859. }
  7860. return this._renderingCanvas.height;
  7861. };
  7862. Engine.prototype.getRenderingCanvas = function () {
  7863. return this._renderingCanvas;
  7864. };
  7865. Engine.prototype.getRenderingCanvasClientRect = function () {
  7866. return this._renderingCanvas.getBoundingClientRect();
  7867. };
  7868. Engine.prototype.setHardwareScalingLevel = function (level) {
  7869. this._hardwareScalingLevel = level;
  7870. this.resize();
  7871. };
  7872. Engine.prototype.getHardwareScalingLevel = function () {
  7873. return this._hardwareScalingLevel;
  7874. };
  7875. Engine.prototype.getLoadedTexturesCache = function () {
  7876. return this._loadedTexturesCache;
  7877. };
  7878. Engine.prototype.getCaps = function () {
  7879. return this._caps;
  7880. };
  7881. Object.defineProperty(Engine.prototype, "drawCalls", {
  7882. get: function () {
  7883. return this._drawCalls.current;
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7889. get: function () {
  7890. return this._drawCalls;
  7891. },
  7892. enumerable: true,
  7893. configurable: true
  7894. });
  7895. Engine.prototype.getDepthFunction = function () {
  7896. return this._depthCullingState.depthFunc;
  7897. };
  7898. Engine.prototype.setDepthFunction = function (depthFunc) {
  7899. this._depthCullingState.depthFunc = depthFunc;
  7900. };
  7901. Engine.prototype.setDepthFunctionToGreater = function () {
  7902. this._depthCullingState.depthFunc = this._gl.GREATER;
  7903. };
  7904. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7905. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7906. };
  7907. Engine.prototype.setDepthFunctionToLess = function () {
  7908. this._depthCullingState.depthFunc = this._gl.LESS;
  7909. };
  7910. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7911. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7912. };
  7913. Engine.prototype.getStencilBuffer = function () {
  7914. return this._stencilState.stencilTest;
  7915. };
  7916. Engine.prototype.setStencilBuffer = function (enable) {
  7917. this._stencilState.stencilTest = enable;
  7918. };
  7919. Engine.prototype.getStencilMask = function () {
  7920. return this._stencilState.stencilMask;
  7921. };
  7922. Engine.prototype.setStencilMask = function (mask) {
  7923. this._stencilState.stencilMask = mask;
  7924. };
  7925. Engine.prototype.getStencilFunction = function () {
  7926. return this._stencilState.stencilFunc;
  7927. };
  7928. Engine.prototype.getStencilFunctionReference = function () {
  7929. return this._stencilState.stencilFuncRef;
  7930. };
  7931. Engine.prototype.getStencilFunctionMask = function () {
  7932. return this._stencilState.stencilFuncMask;
  7933. };
  7934. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7935. this._stencilState.stencilFunc = stencilFunc;
  7936. };
  7937. Engine.prototype.setStencilFunctionReference = function (reference) {
  7938. this._stencilState.stencilFuncRef = reference;
  7939. };
  7940. Engine.prototype.setStencilFunctionMask = function (mask) {
  7941. this._stencilState.stencilFuncMask = mask;
  7942. };
  7943. Engine.prototype.getStencilOperationFail = function () {
  7944. return this._stencilState.stencilOpStencilFail;
  7945. };
  7946. Engine.prototype.getStencilOperationDepthFail = function () {
  7947. return this._stencilState.stencilOpDepthFail;
  7948. };
  7949. Engine.prototype.getStencilOperationPass = function () {
  7950. return this._stencilState.stencilOpStencilDepthPass;
  7951. };
  7952. Engine.prototype.setStencilOperationFail = function (operation) {
  7953. this._stencilState.stencilOpStencilFail = operation;
  7954. };
  7955. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7956. this._stencilState.stencilOpDepthFail = operation;
  7957. };
  7958. Engine.prototype.setStencilOperationPass = function (operation) {
  7959. this._stencilState.stencilOpStencilDepthPass = operation;
  7960. };
  7961. Engine.prototype.setDitheringState = function (value) {
  7962. if (value) {
  7963. this._gl.enable(this._gl.DITHER);
  7964. }
  7965. else {
  7966. this._gl.disable(this._gl.DITHER);
  7967. }
  7968. };
  7969. /**
  7970. * stop executing a render loop function and remove it from the execution array
  7971. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7972. */
  7973. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7974. if (!renderFunction) {
  7975. this._activeRenderLoops = [];
  7976. return;
  7977. }
  7978. var index = this._activeRenderLoops.indexOf(renderFunction);
  7979. if (index >= 0) {
  7980. this._activeRenderLoops.splice(index, 1);
  7981. }
  7982. };
  7983. Engine.prototype._renderLoop = function () {
  7984. var shouldRender = true;
  7985. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7986. shouldRender = false;
  7987. }
  7988. if (shouldRender) {
  7989. // Start new frame
  7990. this.beginFrame();
  7991. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7992. var renderFunction = this._activeRenderLoops[index];
  7993. renderFunction();
  7994. }
  7995. // Present
  7996. this.endFrame();
  7997. }
  7998. if (this._activeRenderLoops.length > 0) {
  7999. // Register new frame
  8000. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8001. }
  8002. else {
  8003. this._renderingQueueLaunched = false;
  8004. }
  8005. };
  8006. /**
  8007. * Register and execute a render loop. The engine can have more than one render function.
  8008. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8009. * @example
  8010. * engine.runRenderLoop(function () {
  8011. * scene.render()
  8012. * })
  8013. */
  8014. Engine.prototype.runRenderLoop = function (renderFunction) {
  8015. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8016. return;
  8017. }
  8018. this._activeRenderLoops.push(renderFunction);
  8019. if (!this._renderingQueueLaunched) {
  8020. this._renderingQueueLaunched = true;
  8021. this._bindedRenderFunction = this._renderLoop.bind(this);
  8022. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8023. }
  8024. };
  8025. /**
  8026. * Toggle full screen mode.
  8027. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8028. * @param {any} options - an options object to be sent to the requestFullscreen function
  8029. */
  8030. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8031. if (this.isFullscreen) {
  8032. BABYLON.Tools.ExitFullscreen();
  8033. }
  8034. else {
  8035. this._pointerLockRequested = requestPointerLock;
  8036. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8037. }
  8038. };
  8039. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8040. if (stencil === void 0) { stencil = false; }
  8041. this.applyStates();
  8042. var mode = 0;
  8043. if (backBuffer && color) {
  8044. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8045. mode |= this._gl.COLOR_BUFFER_BIT;
  8046. }
  8047. if (depth) {
  8048. this._gl.clearDepth(1.0);
  8049. mode |= this._gl.DEPTH_BUFFER_BIT;
  8050. }
  8051. if (stencil) {
  8052. this._gl.clearStencil(0);
  8053. mode |= this._gl.STENCIL_BUFFER_BIT;
  8054. }
  8055. this._gl.clear(mode);
  8056. };
  8057. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8058. var gl = this._gl;
  8059. // Save state
  8060. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8061. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8062. // Change state
  8063. gl.enable(gl.SCISSOR_TEST);
  8064. gl.scissor(x, y, width, height);
  8065. // Clear
  8066. this.clear(clearColor, true, true, true);
  8067. // Restore state
  8068. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8069. if (curScissor === true) {
  8070. gl.enable(gl.SCISSOR_TEST);
  8071. }
  8072. else {
  8073. gl.disable(gl.SCISSOR_TEST);
  8074. }
  8075. };
  8076. /**
  8077. * Set the WebGL's viewport
  8078. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8079. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8080. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8081. */
  8082. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8083. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8084. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8085. var x = viewport.x || 0;
  8086. var y = viewport.y || 0;
  8087. this._cachedViewport = viewport;
  8088. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8089. };
  8090. /**
  8091. * Directly set the WebGL Viewport
  8092. * The x, y, width & height are directly passed to the WebGL call
  8093. * @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.
  8094. */
  8095. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8096. var currentViewport = this._cachedViewport;
  8097. this._cachedViewport = null;
  8098. this._gl.viewport(x, y, width, height);
  8099. return currentViewport;
  8100. };
  8101. Engine.prototype.beginFrame = function () {
  8102. this._measureFps();
  8103. };
  8104. Engine.prototype.endFrame = function () {
  8105. //force a flush in case we are using a bad OS.
  8106. if (this._badOS) {
  8107. this.flushFramebuffer();
  8108. }
  8109. //submit frame to the vr device, if enabled
  8110. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8111. this._vrDisplayEnabled.submitFrame();
  8112. }
  8113. };
  8114. /**
  8115. * resize the view according to the canvas' size.
  8116. * @example
  8117. * window.addEventListener("resize", function () {
  8118. * engine.resize();
  8119. * });
  8120. */
  8121. Engine.prototype.resize = function () {
  8122. // We're not resizing the size of the canvas while in VR mode & presenting
  8123. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8124. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8125. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8126. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8127. }
  8128. };
  8129. /**
  8130. * force a specific size of the canvas
  8131. * @param {number} width - the new canvas' width
  8132. * @param {number} height - the new canvas' height
  8133. */
  8134. Engine.prototype.setSize = function (width, height) {
  8135. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8136. return;
  8137. }
  8138. this._renderingCanvas.width = width;
  8139. this._renderingCanvas.height = height;
  8140. for (var index = 0; index < this.scenes.length; index++) {
  8141. var scene = this.scenes[index];
  8142. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8143. var cam = scene.cameras[camIndex];
  8144. cam._currentRenderId = 0;
  8145. }
  8146. }
  8147. if (this.onResizeObservable.hasObservers) {
  8148. this.onResizeObservable.notifyObservers(this);
  8149. }
  8150. };
  8151. //WebVR functions
  8152. Engine.prototype.isVRDevicePresent = function (callback) {
  8153. this.getVRDevice(null, function (device) {
  8154. callback(device !== null);
  8155. });
  8156. };
  8157. Engine.prototype.getVRDevice = function (name, callback) {
  8158. if (!this.vrDisplaysPromise) {
  8159. callback(null);
  8160. return;
  8161. }
  8162. this.vrDisplaysPromise.then(function (devices) {
  8163. if (devices.length > 0) {
  8164. if (name) {
  8165. var found = devices.some(function (device) {
  8166. if (device.displayName === name) {
  8167. callback(device);
  8168. return true;
  8169. }
  8170. else {
  8171. return false;
  8172. }
  8173. });
  8174. if (!found) {
  8175. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8176. callback(devices[0]);
  8177. }
  8178. }
  8179. else {
  8180. //choose the first one
  8181. callback(devices[0]);
  8182. }
  8183. }
  8184. else {
  8185. BABYLON.Tools.Error("No WebVR devices found!");
  8186. callback(null);
  8187. }
  8188. });
  8189. };
  8190. Engine.prototype.initWebVR = function () {
  8191. if (!this.vrDisplaysPromise) {
  8192. this._getVRDisplays();
  8193. }
  8194. };
  8195. Engine.prototype.enableVR = function (vrDevice) {
  8196. this._vrDisplayEnabled = vrDevice;
  8197. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8198. };
  8199. Engine.prototype.disableVR = function () {
  8200. if (this._vrDisplayEnabled) {
  8201. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8202. }
  8203. };
  8204. Engine.prototype._getVRDisplays = function () {
  8205. var _this = this;
  8206. var getWebVRDevices = function (devices) {
  8207. var size = devices.length;
  8208. var i = 0;
  8209. _this._vrDisplays = devices.filter(function (device) {
  8210. return devices[i] instanceof VRDisplay;
  8211. });
  8212. return _this._vrDisplays;
  8213. };
  8214. //using a key due to typescript
  8215. if (navigator.getVRDisplays) {
  8216. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8217. }
  8218. };
  8219. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8220. this._currentRenderTarget = texture;
  8221. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8222. var gl = this._gl;
  8223. if (texture.isCube) {
  8224. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8225. }
  8226. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8227. this.wipeCaches();
  8228. };
  8229. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8230. if (this._currentFramebuffer !== framebuffer) {
  8231. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8232. this._currentFramebuffer = framebuffer;
  8233. }
  8234. };
  8235. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8236. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8237. this._currentRenderTarget = null;
  8238. // If MSAA, we need to bitblt back to main texture
  8239. var gl = this._gl;
  8240. if (texture._MSAAFramebuffer) {
  8241. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8242. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8243. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8244. }
  8245. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8246. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8247. gl.generateMipmap(gl.TEXTURE_2D);
  8248. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8249. }
  8250. if (onBeforeUnbind) {
  8251. if (texture._MSAAFramebuffer) {
  8252. // Bind the correct framebuffer
  8253. this.bindUnboundFramebuffer(texture._framebuffer);
  8254. }
  8255. onBeforeUnbind();
  8256. }
  8257. this.bindUnboundFramebuffer(null);
  8258. };
  8259. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8260. if (texture.generateMipMaps) {
  8261. var gl = this._gl;
  8262. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8263. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8264. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8265. }
  8266. };
  8267. Engine.prototype.flushFramebuffer = function () {
  8268. this._gl.flush();
  8269. };
  8270. Engine.prototype.restoreDefaultFramebuffer = function () {
  8271. this._currentRenderTarget = null;
  8272. this.bindUnboundFramebuffer(null);
  8273. if (this._cachedViewport) {
  8274. this.setViewport(this._cachedViewport);
  8275. }
  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. var compiledEffect = this._compiledEffects[name];
  8716. if (onCompiled && compiledEffect.isReady()) {
  8717. onCompiled(compiledEffect);
  8718. }
  8719. return compiledEffect;
  8720. }
  8721. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8722. effect._key = name;
  8723. this._compiledEffects[name] = effect;
  8724. return effect;
  8725. };
  8726. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8727. if (uniformsNames === void 0) { uniformsNames = []; }
  8728. if (samplers === void 0) { samplers = []; }
  8729. if (defines === void 0) { defines = ""; }
  8730. return this.createEffect({
  8731. vertex: "particles",
  8732. fragmentElement: fragmentName
  8733. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8734. };
  8735. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8736. context = context || this._gl;
  8737. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8738. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8739. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8740. var shaderProgram = context.createProgram();
  8741. context.attachShader(shaderProgram, vertexShader);
  8742. context.attachShader(shaderProgram, fragmentShader);
  8743. context.linkProgram(shaderProgram);
  8744. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8745. if (!linked) {
  8746. var error = context.getProgramInfoLog(shaderProgram);
  8747. if (error) {
  8748. throw new Error(error);
  8749. }
  8750. }
  8751. context.deleteShader(vertexShader);
  8752. context.deleteShader(fragmentShader);
  8753. return shaderProgram;
  8754. };
  8755. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8756. var results = [];
  8757. for (var index = 0; index < uniformsNames.length; index++) {
  8758. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8759. }
  8760. return results;
  8761. };
  8762. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8763. var results = [];
  8764. for (var index = 0; index < attributesNames.length; index++) {
  8765. try {
  8766. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8767. }
  8768. catch (e) {
  8769. results.push(-1);
  8770. }
  8771. }
  8772. return results;
  8773. };
  8774. Engine.prototype.enableEffect = function (effect) {
  8775. // Use program
  8776. this.setProgram(effect.getProgram());
  8777. this._currentEffect = effect;
  8778. if (effect.onBind) {
  8779. effect.onBind(effect);
  8780. }
  8781. effect.onBindObservable.notifyObservers(effect);
  8782. };
  8783. Engine.prototype.setIntArray = function (uniform, array) {
  8784. if (!uniform)
  8785. return;
  8786. this._gl.uniform1iv(uniform, array);
  8787. };
  8788. Engine.prototype.setIntArray2 = function (uniform, array) {
  8789. if (!uniform || array.length % 2 !== 0)
  8790. return;
  8791. this._gl.uniform2iv(uniform, array);
  8792. };
  8793. Engine.prototype.setIntArray3 = function (uniform, array) {
  8794. if (!uniform || array.length % 3 !== 0)
  8795. return;
  8796. this._gl.uniform3iv(uniform, array);
  8797. };
  8798. Engine.prototype.setIntArray4 = function (uniform, array) {
  8799. if (!uniform || array.length % 4 !== 0)
  8800. return;
  8801. this._gl.uniform4iv(uniform, array);
  8802. };
  8803. Engine.prototype.setFloatArray = function (uniform, array) {
  8804. if (!uniform)
  8805. return;
  8806. this._gl.uniform1fv(uniform, array);
  8807. };
  8808. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8809. if (!uniform || array.length % 2 !== 0)
  8810. return;
  8811. this._gl.uniform2fv(uniform, array);
  8812. };
  8813. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8814. if (!uniform || array.length % 3 !== 0)
  8815. return;
  8816. this._gl.uniform3fv(uniform, array);
  8817. };
  8818. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8819. if (!uniform || array.length % 4 !== 0)
  8820. return;
  8821. this._gl.uniform4fv(uniform, array);
  8822. };
  8823. Engine.prototype.setArray = function (uniform, array) {
  8824. if (!uniform)
  8825. return;
  8826. this._gl.uniform1fv(uniform, array);
  8827. };
  8828. Engine.prototype.setArray2 = function (uniform, array) {
  8829. if (!uniform || array.length % 2 !== 0)
  8830. return;
  8831. this._gl.uniform2fv(uniform, array);
  8832. };
  8833. Engine.prototype.setArray3 = function (uniform, array) {
  8834. if (!uniform || array.length % 3 !== 0)
  8835. return;
  8836. this._gl.uniform3fv(uniform, array);
  8837. };
  8838. Engine.prototype.setArray4 = function (uniform, array) {
  8839. if (!uniform || array.length % 4 !== 0)
  8840. return;
  8841. this._gl.uniform4fv(uniform, array);
  8842. };
  8843. Engine.prototype.setMatrices = function (uniform, matrices) {
  8844. if (!uniform)
  8845. return;
  8846. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8847. };
  8848. Engine.prototype.setMatrix = function (uniform, matrix) {
  8849. if (!uniform)
  8850. return;
  8851. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8852. };
  8853. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8854. if (!uniform)
  8855. return;
  8856. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8857. };
  8858. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8859. if (!uniform)
  8860. return;
  8861. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8862. };
  8863. Engine.prototype.setFloat = function (uniform, value) {
  8864. if (!uniform)
  8865. return;
  8866. this._gl.uniform1f(uniform, value);
  8867. };
  8868. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8869. if (!uniform)
  8870. return;
  8871. this._gl.uniform2f(uniform, x, y);
  8872. };
  8873. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8874. if (!uniform)
  8875. return;
  8876. this._gl.uniform3f(uniform, x, y, z);
  8877. };
  8878. Engine.prototype.setBool = function (uniform, bool) {
  8879. if (!uniform)
  8880. return;
  8881. this._gl.uniform1i(uniform, bool);
  8882. };
  8883. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8884. if (!uniform)
  8885. return;
  8886. this._gl.uniform4f(uniform, x, y, z, w);
  8887. };
  8888. Engine.prototype.setColor3 = function (uniform, color3) {
  8889. if (!uniform)
  8890. return;
  8891. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8892. };
  8893. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8894. if (!uniform)
  8895. return;
  8896. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8897. };
  8898. // States
  8899. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8900. if (zOffset === void 0) { zOffset = 0; }
  8901. if (reverseSide === void 0) { reverseSide = false; }
  8902. // Culling
  8903. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8904. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8905. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8906. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8907. if (culling) {
  8908. this._depthCullingState.cullFace = cullFace;
  8909. this._depthCullingState.cull = true;
  8910. }
  8911. else {
  8912. this._depthCullingState.cull = false;
  8913. }
  8914. }
  8915. // Z offset
  8916. this.setZOffset(zOffset);
  8917. };
  8918. Engine.prototype.setZOffset = function (value) {
  8919. this._depthCullingState.zOffset = value;
  8920. };
  8921. Engine.prototype.getZOffset = function () {
  8922. return this._depthCullingState.zOffset;
  8923. };
  8924. Engine.prototype.setDepthBuffer = function (enable) {
  8925. this._depthCullingState.depthTest = enable;
  8926. };
  8927. Engine.prototype.getDepthWrite = function () {
  8928. return this._depthCullingState.depthMask;
  8929. };
  8930. Engine.prototype.setDepthWrite = function (enable) {
  8931. this._depthCullingState.depthMask = enable;
  8932. };
  8933. Engine.prototype.setColorWrite = function (enable) {
  8934. this._gl.colorMask(enable, enable, enable, enable);
  8935. };
  8936. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8937. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8938. };
  8939. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8940. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8941. if (this._alphaMode === mode) {
  8942. return;
  8943. }
  8944. switch (mode) {
  8945. case Engine.ALPHA_DISABLE:
  8946. this._alphaState.alphaBlend = false;
  8947. break;
  8948. case Engine.ALPHA_PREMULTIPLIED:
  8949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8950. this._alphaState.alphaBlend = true;
  8951. break;
  8952. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8954. this._alphaState.alphaBlend = true;
  8955. break;
  8956. case Engine.ALPHA_COMBINE:
  8957. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8958. this._alphaState.alphaBlend = true;
  8959. break;
  8960. case Engine.ALPHA_ONEONE:
  8961. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8962. this._alphaState.alphaBlend = true;
  8963. break;
  8964. case Engine.ALPHA_ADD:
  8965. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8966. this._alphaState.alphaBlend = true;
  8967. break;
  8968. case Engine.ALPHA_SUBTRACT:
  8969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8970. this._alphaState.alphaBlend = true;
  8971. break;
  8972. case Engine.ALPHA_MULTIPLY:
  8973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8974. this._alphaState.alphaBlend = true;
  8975. break;
  8976. case Engine.ALPHA_MAXIMIZED:
  8977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8978. this._alphaState.alphaBlend = true;
  8979. break;
  8980. case Engine.ALPHA_INTERPOLATE:
  8981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8982. this._alphaState.alphaBlend = true;
  8983. break;
  8984. case Engine.ALPHA_SCREENMODE:
  8985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8986. this._alphaState.alphaBlend = true;
  8987. break;
  8988. }
  8989. if (!noDepthWriteChange) {
  8990. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8991. }
  8992. this._alphaMode = mode;
  8993. };
  8994. Engine.prototype.getAlphaMode = function () {
  8995. return this._alphaMode;
  8996. };
  8997. Engine.prototype.setAlphaTesting = function (enable) {
  8998. this._alphaTest = enable;
  8999. };
  9000. Engine.prototype.getAlphaTesting = function () {
  9001. return !!this._alphaTest;
  9002. };
  9003. // Textures
  9004. Engine.prototype.wipeCaches = function (bruteForce) {
  9005. if (this.preventCacheWipeBetweenFrames) {
  9006. return;
  9007. }
  9008. this.resetTextureCache();
  9009. this._currentEffect = null;
  9010. // 6/8/2017: deltakosh: Should not be required anymore.
  9011. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9012. if (bruteForce) {
  9013. this._stencilState.reset();
  9014. this._depthCullingState.reset();
  9015. this.setDepthFunctionToLessOrEqual();
  9016. this._alphaState.reset();
  9017. }
  9018. this._cachedVertexBuffers = null;
  9019. this._cachedIndexBuffer = null;
  9020. this._cachedEffectForVertexBuffers = null;
  9021. this._unBindVertexArrayObject();
  9022. this.bindIndexBuffer(null);
  9023. this.bindArrayBuffer(null);
  9024. };
  9025. /**
  9026. * Set the compressed texture format to use, based on the formats you have, and the formats
  9027. * supported by the hardware / browser.
  9028. *
  9029. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9030. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9031. * to API arguments needed to compressed textures. This puts the burden on the container
  9032. * generator to house the arcane code for determining these for current & future formats.
  9033. *
  9034. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9035. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9036. *
  9037. * Note: The result of this call is not taken into account when a texture is base64.
  9038. *
  9039. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9040. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9041. *
  9042. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9043. * @returns The extension selected.
  9044. */
  9045. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9046. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9047. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9048. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9049. return this._textureFormatInUse = this._texturesSupported[i];
  9050. }
  9051. }
  9052. }
  9053. // actively set format to nothing, to allow this to be called more than once
  9054. // and possibly fail the 2nd time
  9055. return this._textureFormatInUse = null;
  9056. };
  9057. /**
  9058. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9059. * @param {string} urlArg- This contains one of the following:
  9060. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9061. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9062. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9063. *
  9064. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9065. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9066. * @param {Scene} scene- Needed for loading to the correct scene.
  9067. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9068. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9069. * @param {callback} onError- Optional callback to be called upon failure.
  9070. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9071. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9072. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9073. *
  9074. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9075. */
  9076. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9077. var _this = this;
  9078. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9079. if (onLoad === void 0) { onLoad = null; }
  9080. if (onError === void 0) { onError = null; }
  9081. if (buffer === void 0) { buffer = null; }
  9082. var texture = fallBack ? fallBack : this._gl.createTexture();
  9083. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9084. var fromData = url.substr(0, 5) === "data:";
  9085. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9086. // establish the file extension, if possible
  9087. var lastDot = url.lastIndexOf('.');
  9088. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9089. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9090. if (isDDS) {
  9091. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9092. }
  9093. var isTGA = (extension === ".tga");
  9094. // determine if a ktx file should be substituted
  9095. var isKTX = false;
  9096. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9097. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9098. isKTX = true;
  9099. }
  9100. scene._addPendingData(texture);
  9101. texture.url = url;
  9102. texture.noMipmap = noMipmap;
  9103. texture.references = 1;
  9104. texture.samplingMode = samplingMode;
  9105. texture.onLoadedCallbacks = [];
  9106. if (onLoad) {
  9107. texture.onLoadedCallbacks.push(onLoad);
  9108. }
  9109. if (!fallBack)
  9110. this._loadedTexturesCache.push(texture);
  9111. var onerror = function () {
  9112. scene._removePendingData(texture);
  9113. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9114. if (isKTX) {
  9115. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9116. }
  9117. else if (onError) {
  9118. onError();
  9119. }
  9120. };
  9121. var callback;
  9122. // processing for non-image formats
  9123. if (isKTX || isTGA || isDDS) {
  9124. if (isKTX) {
  9125. callback = function (data) {
  9126. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9127. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9128. ktx.uploadLevels(_this._gl, !noMipmap);
  9129. }, samplingMode);
  9130. };
  9131. }
  9132. else if (isTGA) {
  9133. callback = function (arrayBuffer) {
  9134. var data = new Uint8Array(arrayBuffer);
  9135. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9136. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9137. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9138. }, samplingMode);
  9139. };
  9140. }
  9141. else if (isDDS) {
  9142. callback = function (data) {
  9143. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9144. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9145. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9146. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9147. }, samplingMode);
  9148. };
  9149. }
  9150. if (!buffer) {
  9151. BABYLON.Tools.LoadFile(url, function (data) {
  9152. callback(data);
  9153. }, null, scene.database, true, onerror);
  9154. }
  9155. else {
  9156. callback(buffer);
  9157. }
  9158. // image format processing
  9159. }
  9160. else {
  9161. var onload = function (img) {
  9162. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9163. var isPot = (img.width === potWidth && img.height === potHeight);
  9164. if (!isPot) {
  9165. _this._prepareWorkingCanvas();
  9166. _this._workingCanvas.width = potWidth;
  9167. _this._workingCanvas.height = potHeight;
  9168. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9169. _this._workingContext.imageSmoothingEnabled = false;
  9170. _this._workingContext.mozImageSmoothingEnabled = false;
  9171. _this._workingContext.oImageSmoothingEnabled = false;
  9172. _this._workingContext.webkitImageSmoothingEnabled = false;
  9173. _this._workingContext.msImageSmoothingEnabled = false;
  9174. }
  9175. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9176. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9177. _this._workingContext.imageSmoothingEnabled = true;
  9178. _this._workingContext.mozImageSmoothingEnabled = true;
  9179. _this._workingContext.oImageSmoothingEnabled = true;
  9180. _this._workingContext.webkitImageSmoothingEnabled = true;
  9181. _this._workingContext.msImageSmoothingEnabled = true;
  9182. }
  9183. }
  9184. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9185. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9186. }, samplingMode);
  9187. };
  9188. if (!fromData || isBase64)
  9189. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9190. else if (buffer instanceof Array || typeof buffer === "string")
  9191. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9192. else
  9193. onload(buffer);
  9194. }
  9195. return texture;
  9196. };
  9197. Engine.prototype._getInternalFormat = function (format) {
  9198. var internalFormat = this._gl.RGBA;
  9199. switch (format) {
  9200. case Engine.TEXTUREFORMAT_ALPHA:
  9201. internalFormat = this._gl.ALPHA;
  9202. break;
  9203. case Engine.TEXTUREFORMAT_LUMINANCE:
  9204. internalFormat = this._gl.LUMINANCE;
  9205. break;
  9206. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9207. internalFormat = this._gl.LUMINANCE_ALPHA;
  9208. break;
  9209. case Engine.TEXTUREFORMAT_RGB:
  9210. internalFormat = this._gl.RGB;
  9211. break;
  9212. case Engine.TEXTUREFORMAT_RGBA:
  9213. internalFormat = this._gl.RGBA;
  9214. break;
  9215. }
  9216. return internalFormat;
  9217. };
  9218. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9219. if (compression === void 0) { compression = null; }
  9220. var internalFormat = this._getInternalFormat(format);
  9221. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9222. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9223. if (texture._width % 4 !== 0) {
  9224. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9225. }
  9226. if (compression) {
  9227. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9228. }
  9229. else {
  9230. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9231. }
  9232. if (texture.generateMipMaps) {
  9233. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9234. }
  9235. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9236. this.resetTextureCache();
  9237. texture.isReady = true;
  9238. };
  9239. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9240. if (compression === void 0) { compression = null; }
  9241. var texture = this._gl.createTexture();
  9242. texture._baseWidth = width;
  9243. texture._baseHeight = height;
  9244. texture._width = width;
  9245. texture._height = height;
  9246. texture.references = 1;
  9247. this.updateRawTexture(texture, data, format, invertY, compression);
  9248. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9249. // Filters
  9250. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9251. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9252. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9253. if (generateMipMaps) {
  9254. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9255. }
  9256. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9257. texture.samplingMode = samplingMode;
  9258. this._loadedTexturesCache.push(texture);
  9259. return texture;
  9260. };
  9261. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9262. var texture = this._gl.createTexture();
  9263. texture._baseWidth = width;
  9264. texture._baseHeight = height;
  9265. if (generateMipMaps) {
  9266. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9267. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9268. }
  9269. this.resetTextureCache();
  9270. texture._width = width;
  9271. texture._height = height;
  9272. texture.isReady = false;
  9273. texture.generateMipMaps = generateMipMaps;
  9274. texture.references = 1;
  9275. texture.samplingMode = samplingMode;
  9276. this.updateTextureSamplingMode(samplingMode, texture);
  9277. this._loadedTexturesCache.push(texture);
  9278. return texture;
  9279. };
  9280. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9281. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9282. if (texture.isCube) {
  9283. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9284. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9285. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9286. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9287. }
  9288. else {
  9289. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9290. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9291. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9293. }
  9294. texture.samplingMode = samplingMode;
  9295. };
  9296. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9297. if (premulAlpha === void 0) { premulAlpha = false; }
  9298. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9299. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9300. if (premulAlpha) {
  9301. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9302. }
  9303. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9304. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9305. if (texture.generateMipMaps) {
  9306. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9307. }
  9308. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9309. if (premulAlpha) {
  9310. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9311. }
  9312. this.resetTextureCache();
  9313. texture.isReady = true;
  9314. };
  9315. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9316. if (texture._isDisabled) {
  9317. return;
  9318. }
  9319. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9320. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9321. try {
  9322. // Testing video texture support
  9323. if (this._videoTextureSupported === undefined) {
  9324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9325. if (this._gl.getError() !== 0) {
  9326. this._videoTextureSupported = false;
  9327. }
  9328. else {
  9329. this._videoTextureSupported = true;
  9330. }
  9331. }
  9332. // Copy video through the current working canvas if video texture is not supported
  9333. if (!this._videoTextureSupported) {
  9334. if (!texture._workingCanvas) {
  9335. texture._workingCanvas = document.createElement("canvas");
  9336. texture._workingContext = texture._workingCanvas.getContext("2d");
  9337. texture._workingCanvas.width = texture._width;
  9338. texture._workingCanvas.height = texture._height;
  9339. }
  9340. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9341. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9342. }
  9343. else {
  9344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9345. }
  9346. if (texture.generateMipMaps) {
  9347. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9348. }
  9349. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9350. this.resetTextureCache();
  9351. texture.isReady = true;
  9352. }
  9353. catch (ex) {
  9354. // Something unexpected
  9355. // Let's disable the texture
  9356. texture._isDisabled = true;
  9357. }
  9358. };
  9359. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9360. // old version had a "generateMipMaps" arg instead of options.
  9361. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9362. // in the same way, generateDepthBuffer is defaulted to true
  9363. var generateMipMaps = false;
  9364. var generateDepthBuffer = true;
  9365. var generateStencilBuffer = false;
  9366. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9367. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9368. if (options !== undefined) {
  9369. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9370. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9371. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9372. type = options.type === undefined ? type : options.type;
  9373. if (options.samplingMode !== undefined) {
  9374. samplingMode = options.samplingMode;
  9375. }
  9376. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9377. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9378. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9379. }
  9380. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9381. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9382. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9383. }
  9384. }
  9385. var gl = this._gl;
  9386. var texture = gl.createTexture();
  9387. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9388. var width = size.width || size;
  9389. var height = size.height || size;
  9390. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9391. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9392. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9393. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9394. }
  9395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9399. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9400. // Create the framebuffer
  9401. var framebuffer = gl.createFramebuffer();
  9402. this.bindUnboundFramebuffer(framebuffer);
  9403. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9404. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9405. if (generateMipMaps) {
  9406. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9407. }
  9408. // Unbind
  9409. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9410. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9411. this.bindUnboundFramebuffer(null);
  9412. texture._framebuffer = framebuffer;
  9413. texture._baseWidth = width;
  9414. texture._baseHeight = height;
  9415. texture._width = width;
  9416. texture._height = height;
  9417. texture.isReady = true;
  9418. texture.samples = 1;
  9419. texture.generateMipMaps = generateMipMaps;
  9420. texture.references = 1;
  9421. texture.samplingMode = samplingMode;
  9422. texture.type = type;
  9423. texture._generateDepthBuffer = generateDepthBuffer;
  9424. texture._generateStencilBuffer = generateStencilBuffer;
  9425. this.resetTextureCache();
  9426. this._loadedTexturesCache.push(texture);
  9427. return texture;
  9428. };
  9429. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9430. var generateMipMaps = false;
  9431. var generateDepthBuffer = true;
  9432. var generateStencilBuffer = false;
  9433. var generateDepthTexture = false;
  9434. var textureCount = 1;
  9435. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9436. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9437. var types = [], samplingModes = [];
  9438. if (options !== undefined) {
  9439. generateMipMaps = options.generateMipMaps;
  9440. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9441. generateStencilBuffer = options.generateStencilBuffer;
  9442. generateDepthTexture = options.generateDepthTexture;
  9443. textureCount = options.textureCount || 1;
  9444. if (options.types) {
  9445. types = options.types;
  9446. }
  9447. if (options.samplingModes) {
  9448. samplingModes = options.samplingModes;
  9449. }
  9450. }
  9451. var gl = this._gl;
  9452. // Create the framebuffer
  9453. var framebuffer = gl.createFramebuffer();
  9454. this.bindUnboundFramebuffer(framebuffer);
  9455. var width = size.width || size;
  9456. var height = size.height || size;
  9457. var textures = [];
  9458. var attachments = [];
  9459. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9460. for (var i = 0; i < textureCount; i++) {
  9461. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9462. var type = types[i] || defaultType;
  9463. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9464. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9465. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9466. }
  9467. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9468. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9469. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9470. }
  9471. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9472. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9473. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9474. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9475. }
  9476. var texture = gl.createTexture();
  9477. var attachment = gl["COLOR_ATTACHMENT" + i];
  9478. textures.push(texture);
  9479. attachments.push(attachment);
  9480. gl.activeTexture(gl["TEXTURE" + i]);
  9481. gl.bindTexture(gl.TEXTURE_2D, texture);
  9482. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9483. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9484. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9486. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9487. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9488. if (generateMipMaps) {
  9489. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9490. }
  9491. // Unbind
  9492. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9493. texture._framebuffer = framebuffer;
  9494. texture._depthStencilBuffer = depthStencilBuffer;
  9495. texture._baseWidth = width;
  9496. texture._baseHeight = height;
  9497. texture._width = width;
  9498. texture._height = height;
  9499. texture.isReady = true;
  9500. texture.samples = 1;
  9501. texture.generateMipMaps = generateMipMaps;
  9502. texture.references = 1;
  9503. texture.samplingMode = samplingMode;
  9504. texture.type = type;
  9505. texture._generateDepthBuffer = generateDepthBuffer;
  9506. texture._generateStencilBuffer = generateStencilBuffer;
  9507. this._loadedTexturesCache.push(texture);
  9508. }
  9509. if (generateDepthTexture) {
  9510. // Depth texture
  9511. var depthTexture = gl.createTexture();
  9512. gl.activeTexture(gl.TEXTURE0);
  9513. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9514. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9515. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9516. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9517. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9518. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9519. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9520. depthTexture._framebuffer = framebuffer;
  9521. depthTexture._baseWidth = width;
  9522. depthTexture._baseHeight = height;
  9523. depthTexture._width = width;
  9524. depthTexture._height = height;
  9525. depthTexture.isReady = true;
  9526. depthTexture.samples = 1;
  9527. depthTexture.generateMipMaps = generateMipMaps;
  9528. depthTexture.references = 1;
  9529. depthTexture.samplingMode = gl.NEAREST;
  9530. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9531. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9532. textures.push(depthTexture);
  9533. this._loadedTexturesCache.push(depthTexture);
  9534. }
  9535. gl.drawBuffers(attachments);
  9536. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9537. this.bindUnboundFramebuffer(null);
  9538. this.resetTextureCache();
  9539. return textures;
  9540. };
  9541. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9542. if (samples === void 0) { samples = 1; }
  9543. var depthStencilBuffer = null;
  9544. var gl = this._gl;
  9545. // Create the depth/stencil buffer
  9546. if (generateStencilBuffer) {
  9547. depthStencilBuffer = gl.createRenderbuffer();
  9548. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9549. if (samples > 1) {
  9550. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9551. }
  9552. else {
  9553. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9554. }
  9555. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9556. }
  9557. else if (generateDepthBuffer) {
  9558. depthStencilBuffer = gl.createRenderbuffer();
  9559. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9560. if (samples > 1) {
  9561. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9562. }
  9563. else {
  9564. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9565. }
  9566. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9567. }
  9568. return depthStencilBuffer;
  9569. };
  9570. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9571. if (this.webGLVersion < 2) {
  9572. return 1;
  9573. }
  9574. if (texture.samples === samples) {
  9575. return samples;
  9576. }
  9577. var gl = this._gl;
  9578. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9579. // Dispose previous render buffers
  9580. if (texture._depthStencilBuffer) {
  9581. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9582. }
  9583. if (texture._MSAAFramebuffer) {
  9584. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9585. }
  9586. if (texture._MSAARenderBuffer) {
  9587. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9588. }
  9589. if (samples > 1) {
  9590. texture._MSAAFramebuffer = gl.createFramebuffer();
  9591. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9592. var colorRenderbuffer = gl.createRenderbuffer();
  9593. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9594. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9595. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9596. texture._MSAARenderBuffer = colorRenderbuffer;
  9597. }
  9598. else {
  9599. this.bindUnboundFramebuffer(texture._framebuffer);
  9600. }
  9601. texture.samples = samples;
  9602. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9603. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9604. this.bindUnboundFramebuffer(null);
  9605. return samples;
  9606. };
  9607. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9608. var gl = this._gl;
  9609. var texture = gl.createTexture();
  9610. var generateMipMaps = true;
  9611. var generateDepthBuffer = true;
  9612. var generateStencilBuffer = false;
  9613. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9614. if (options !== undefined) {
  9615. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9617. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9618. if (options.samplingMode !== undefined) {
  9619. samplingMode = options.samplingMode;
  9620. }
  9621. }
  9622. texture.isCube = true;
  9623. texture.references = 1;
  9624. texture.generateMipMaps = generateMipMaps;
  9625. texture.references = 1;
  9626. texture.samples = 1;
  9627. texture.samplingMode = samplingMode;
  9628. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9629. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9630. for (var face = 0; face < 6; face++) {
  9631. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9632. }
  9633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9637. // Create the framebuffer
  9638. var framebuffer = gl.createFramebuffer();
  9639. this.bindUnboundFramebuffer(framebuffer);
  9640. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9641. // Mipmaps
  9642. if (texture.generateMipMaps) {
  9643. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9644. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9645. }
  9646. // Unbind
  9647. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9648. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9649. this.bindUnboundFramebuffer(null);
  9650. texture._framebuffer = framebuffer;
  9651. texture._width = size;
  9652. texture._height = size;
  9653. texture.isReady = true;
  9654. this.resetTextureCache();
  9655. this._loadedTexturesCache.push(texture);
  9656. return texture;
  9657. };
  9658. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9659. var _this = this;
  9660. if (onLoad === void 0) { onLoad = null; }
  9661. if (onError === void 0) { onError = null; }
  9662. var gl = this._gl;
  9663. var texture = gl.createTexture();
  9664. texture.isCube = true;
  9665. texture.url = rootUrl;
  9666. texture.references = 1;
  9667. texture.onLoadedCallbacks = [];
  9668. var isKTX = false;
  9669. var lastDot = rootUrl.lastIndexOf('.');
  9670. var extension = rootUrl.substring(lastDot).toLowerCase();
  9671. if (this._textureFormatInUse) {
  9672. extension = this._textureFormatInUse;
  9673. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9674. isKTX = true;
  9675. }
  9676. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9677. if (isDDS) {
  9678. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9679. }
  9680. if (isKTX) {
  9681. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9682. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9683. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9684. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9685. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9686. ktx.uploadLevels(_this._gl, !noMipmap);
  9687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9692. _this.resetTextureCache();
  9693. texture._width = ktx.pixelWidth;
  9694. texture._height = ktx.pixelHeight;
  9695. texture.isReady = true;
  9696. }, null, null, true, onError);
  9697. }
  9698. else if (isDDS) {
  9699. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9700. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9701. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9703. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9704. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9705. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9706. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9707. }
  9708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9712. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9713. _this.resetTextureCache();
  9714. texture._width = info.width;
  9715. texture._height = info.height;
  9716. texture.isReady = true;
  9717. }, null, null, true, onError);
  9718. }
  9719. else {
  9720. cascadeLoad(rootUrl, scene, function (imgs) {
  9721. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9722. var height = width;
  9723. _this._prepareWorkingCanvas();
  9724. _this._workingCanvas.width = width;
  9725. _this._workingCanvas.height = height;
  9726. var faces = [
  9727. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9728. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9729. ];
  9730. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9731. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9732. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9733. for (var index = 0; index < faces.length; index++) {
  9734. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9735. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9736. }
  9737. if (!noMipmap) {
  9738. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9739. }
  9740. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9741. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9744. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9745. _this.resetTextureCache();
  9746. texture._width = width;
  9747. texture._height = height;
  9748. texture.isReady = true;
  9749. texture.onLoadedCallbacks.forEach(function (callback) {
  9750. callback();
  9751. });
  9752. if (onLoad) {
  9753. onLoad();
  9754. }
  9755. }, files, onError);
  9756. }
  9757. this._loadedTexturesCache.push(texture);
  9758. return texture;
  9759. };
  9760. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9761. texture._width = width;
  9762. texture._height = height;
  9763. texture._size = width * height;
  9764. texture._baseWidth = width;
  9765. texture._baseHeight = height;
  9766. };
  9767. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9768. if (compression === void 0) { compression = null; }
  9769. if (level === void 0) { level = 0; }
  9770. var gl = this._gl;
  9771. var textureType = this._getWebGLTextureType(type);
  9772. var internalFormat = this._getInternalFormat(format);
  9773. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9774. var needConversion = false;
  9775. if (internalFormat === gl.RGB) {
  9776. internalFormat = gl.RGBA;
  9777. needConversion = true;
  9778. }
  9779. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9780. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9781. if (texture._width % 4 !== 0) {
  9782. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9783. }
  9784. var facesIndex = [
  9785. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9786. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9787. ];
  9788. // Data are known to be in +X +Y +Z -X -Y -Z
  9789. for (var index = 0; index < facesIndex.length; index++) {
  9790. var faceData = data[index];
  9791. if (compression) {
  9792. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9793. }
  9794. else {
  9795. if (needConversion) {
  9796. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9797. }
  9798. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9799. }
  9800. }
  9801. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9802. if (isPot && texture.generateMipMaps && level === 0) {
  9803. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9804. }
  9805. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9806. this.resetTextureCache();
  9807. texture.isReady = true;
  9808. };
  9809. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9810. if (compression === void 0) { compression = null; }
  9811. var gl = this._gl;
  9812. var texture = gl.createTexture();
  9813. texture.isCube = true;
  9814. texture.references = 1;
  9815. var textureType = this._getWebGLTextureType(type);
  9816. var internalFormat = this._getInternalFormat(format);
  9817. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9818. var needConversion = false;
  9819. if (internalFormat === gl.RGB) {
  9820. internalFormat = gl.RGBA;
  9821. needConversion = true;
  9822. }
  9823. var width = size;
  9824. var height = width;
  9825. texture._width = width;
  9826. texture._height = height;
  9827. // Double check on POT to generate Mips.
  9828. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9829. if (!isPot) {
  9830. generateMipMaps = false;
  9831. }
  9832. texture.generateMipMaps = generateMipMaps;
  9833. // Upload data if needed. The texture won t be ready until then.
  9834. if (data) {
  9835. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9836. }
  9837. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9838. // Filters
  9839. if (data && generateMipMaps) {
  9840. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9841. }
  9842. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9845. }
  9846. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9849. }
  9850. else {
  9851. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9854. }
  9855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9857. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9858. this._loadedTexturesCache.push(texture);
  9859. return texture;
  9860. };
  9861. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9862. var _this = this;
  9863. if (onLoad === void 0) { onLoad = null; }
  9864. if (onError === void 0) { onError = null; }
  9865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9866. if (invertY === void 0) { invertY = false; }
  9867. var gl = this._gl;
  9868. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9869. scene._addPendingData(texture);
  9870. texture.url = url;
  9871. var onerror = function () {
  9872. scene._removePendingData(texture);
  9873. if (onError) {
  9874. onError();
  9875. }
  9876. };
  9877. var internalCallback = function (data) {
  9878. var rgbeDataArrays = callback(data);
  9879. var facesIndex = [
  9880. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9881. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9882. ];
  9883. var width = texture._width;
  9884. var height = texture._height;
  9885. if (mipmmapGenerator) {
  9886. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9887. // I ll remove ASAP.
  9888. var textureType = _this._getWebGLTextureType(type);
  9889. var internalFormat = _this._getInternalFormat(format);
  9890. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9891. var needConversion = false;
  9892. if (internalFormat === gl.RGB) {
  9893. internalFormat = gl.RGBA;
  9894. needConversion = true;
  9895. }
  9896. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9897. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9898. var arrayTemp = [];
  9899. // Data are known to be in +X +Y +Z -X -Y -Z
  9900. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9901. arrayTemp.push(rgbeDataArrays[0]); // +X
  9902. arrayTemp.push(rgbeDataArrays[3]); // -X
  9903. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9904. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9905. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9906. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9907. var mipData = mipmmapGenerator(arrayTemp);
  9908. // mipData is order in +X -X +Y -Y +Z -Z
  9909. var mipFaces = [0, 2, 4, 1, 3, 5];
  9910. for (var level = 0; level < mipData.length; level++) {
  9911. var mipSize = width >> level;
  9912. for (var mipIndex in mipFaces) {
  9913. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9914. if (needConversion) {
  9915. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9916. }
  9917. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9918. }
  9919. }
  9920. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9921. }
  9922. else {
  9923. texture.generateMipMaps = !noMipmap;
  9924. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9925. }
  9926. texture.isReady = true;
  9927. _this.resetTextureCache();
  9928. scene._removePendingData(texture);
  9929. if (onLoad) {
  9930. onLoad();
  9931. }
  9932. };
  9933. BABYLON.Tools.LoadFile(url, function (data) {
  9934. internalCallback(data);
  9935. }, onerror, scene.database, true);
  9936. return texture;
  9937. };
  9938. ;
  9939. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9940. // Create new RGBA data container.
  9941. var rgbaData;
  9942. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9943. rgbaData = new Float32Array(width * height * 4);
  9944. }
  9945. else {
  9946. rgbaData = new Uint32Array(width * height * 4);
  9947. }
  9948. // Convert each pixel.
  9949. for (var x = 0; x < width; x++) {
  9950. for (var y = 0; y < height; y++) {
  9951. var index = (y * width + x) * 3;
  9952. var newIndex = (y * width + x) * 4;
  9953. // Map Old Value to new value.
  9954. rgbaData[newIndex + 0] = rgbData[index + 0];
  9955. rgbaData[newIndex + 1] = rgbData[index + 1];
  9956. rgbaData[newIndex + 2] = rgbData[index + 2];
  9957. // Add fully opaque alpha channel.
  9958. rgbaData[newIndex + 3] = 1;
  9959. }
  9960. }
  9961. return rgbaData;
  9962. };
  9963. Engine.prototype._releaseFramebufferObjects = function (texture) {
  9964. var gl = this._gl;
  9965. if (texture._framebuffer) {
  9966. gl.deleteFramebuffer(texture._framebuffer);
  9967. texture._framebuffer = null;
  9968. }
  9969. if (texture._depthStencilBuffer) {
  9970. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9971. texture._depthStencilBuffer = null;
  9972. }
  9973. if (texture._MSAAFramebuffer) {
  9974. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9975. texture._MSAAFramebuffer = null;
  9976. }
  9977. if (texture._MSAARenderBuffer) {
  9978. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9979. texture._MSAARenderBuffer = null;
  9980. }
  9981. };
  9982. Engine.prototype._releaseTexture = function (texture) {
  9983. var gl = this._gl;
  9984. this._releaseFramebufferObjects(texture);
  9985. gl.deleteTexture(texture);
  9986. // Unbind channels
  9987. this.unbindAllTextures();
  9988. var index = this._loadedTexturesCache.indexOf(texture);
  9989. if (index !== -1) {
  9990. this._loadedTexturesCache.splice(index, 1);
  9991. }
  9992. };
  9993. Engine.prototype.setProgram = function (program) {
  9994. if (this._currentProgram !== program) {
  9995. this._gl.useProgram(program);
  9996. this._currentProgram = program;
  9997. }
  9998. };
  9999. Engine.prototype.bindSamplers = function (effect) {
  10000. this.setProgram(effect.getProgram());
  10001. var samplers = effect.getSamplers();
  10002. for (var index = 0; index < samplers.length; index++) {
  10003. var uniform = effect.getUniform(samplers[index]);
  10004. this._gl.uniform1i(uniform, index);
  10005. }
  10006. this._currentEffect = null;
  10007. };
  10008. Engine.prototype.activateTexture = function (texture) {
  10009. if (this._activeTexture !== texture) {
  10010. this._gl.activeTexture(texture);
  10011. this._activeTexture = texture;
  10012. }
  10013. };
  10014. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10015. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10016. this._gl.bindTexture(target, texture);
  10017. this._activeTexturesCache[this._activeTexture] = texture;
  10018. }
  10019. };
  10020. Engine.prototype._bindTexture = function (channel, texture) {
  10021. if (channel < 0) {
  10022. return;
  10023. }
  10024. this.activateTexture(this._gl.TEXTURE0 + channel);
  10025. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10026. };
  10027. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10028. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10029. };
  10030. Engine.prototype.unbindAllTextures = function () {
  10031. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10032. this.activateTexture(this._gl["TEXTURE" + channel]);
  10033. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10034. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10035. }
  10036. };
  10037. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10038. if (channel < 0) {
  10039. return;
  10040. }
  10041. this._gl.uniform1i(uniform, channel);
  10042. this._setTexture(channel, texture);
  10043. };
  10044. Engine.prototype._setTexture = function (channel, texture) {
  10045. // Not ready?
  10046. if (!texture) {
  10047. if (this._activeTexturesCache[channel] != null) {
  10048. this.activateTexture(this._gl["TEXTURE" + channel]);
  10049. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10050. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10051. }
  10052. return;
  10053. }
  10054. // Video
  10055. var alreadyActivated = false;
  10056. if (texture.video) {
  10057. this.activateTexture(this._gl["TEXTURE" + channel]);
  10058. alreadyActivated = true;
  10059. texture.update();
  10060. }
  10061. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10062. texture.delayLoad();
  10063. return;
  10064. }
  10065. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10066. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10067. if (this._activeTexturesCache[channel] === internalTexture) {
  10068. return;
  10069. }
  10070. if (!alreadyActivated) {
  10071. this.activateTexture(this._gl["TEXTURE" + channel]);
  10072. }
  10073. if (internalTexture.isCube) {
  10074. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10075. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10076. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10077. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10078. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10079. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10080. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10081. }
  10082. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10083. }
  10084. else {
  10085. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10086. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10087. internalTexture._cachedWrapU = texture.wrapU;
  10088. switch (texture.wrapU) {
  10089. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10090. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10091. break;
  10092. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10093. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10094. break;
  10095. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10097. break;
  10098. }
  10099. }
  10100. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10101. internalTexture._cachedWrapV = texture.wrapV;
  10102. switch (texture.wrapV) {
  10103. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10104. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10105. break;
  10106. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10107. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10108. break;
  10109. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10110. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10111. break;
  10112. }
  10113. }
  10114. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10115. }
  10116. };
  10117. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10118. if (channel < 0) {
  10119. return;
  10120. }
  10121. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10122. this._textureUnits = new Int32Array(textures.length);
  10123. }
  10124. for (var i = 0; i < textures.length; i++) {
  10125. this._textureUnits[i] = channel + i;
  10126. }
  10127. this._gl.uniform1iv(uniform, this._textureUnits);
  10128. for (var index = 0; index < textures.length; index++) {
  10129. this._setTexture(channel + index, textures[index]);
  10130. }
  10131. };
  10132. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10133. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10134. var value = texture.anisotropicFilteringLevel;
  10135. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10136. value = 1;
  10137. }
  10138. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10139. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10140. texture._cachedAnisotropicFilteringLevel = value;
  10141. }
  10142. };
  10143. Engine.prototype.readPixels = function (x, y, width, height) {
  10144. var data = new Uint8Array(height * width * 4);
  10145. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10146. return data;
  10147. };
  10148. /**
  10149. * Add an externaly attached data from its key.
  10150. * This method call will fail and return false, if such key already exists.
  10151. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10152. * @param key the unique key that identifies the data
  10153. * @param data the data object to associate to the key for this Engine instance
  10154. * @return true if no such key were already present and the data was added successfully, false otherwise
  10155. */
  10156. Engine.prototype.addExternalData = function (key, data) {
  10157. if (!this._externalData) {
  10158. this._externalData = new BABYLON.StringDictionary();
  10159. }
  10160. return this._externalData.add(key, data);
  10161. };
  10162. /**
  10163. * Get an externaly attached data from its key
  10164. * @param key the unique key that identifies the data
  10165. * @return the associated data, if present (can be null), or undefined if not present
  10166. */
  10167. Engine.prototype.getExternalData = function (key) {
  10168. if (!this._externalData) {
  10169. this._externalData = new BABYLON.StringDictionary();
  10170. }
  10171. return this._externalData.get(key);
  10172. };
  10173. /**
  10174. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10175. * @param key the unique key that identifies the data
  10176. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10177. * @return the associated data, can be null if the factory returned null.
  10178. */
  10179. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10180. if (!this._externalData) {
  10181. this._externalData = new BABYLON.StringDictionary();
  10182. }
  10183. return this._externalData.getOrAddWithFactory(key, factory);
  10184. };
  10185. /**
  10186. * Remove an externaly attached data from the Engine instance
  10187. * @param key the unique key that identifies the data
  10188. * @return true if the data was successfully removed, false if it doesn't exist
  10189. */
  10190. Engine.prototype.removeExternalData = function (key) {
  10191. if (!this._externalData) {
  10192. this._externalData = new BABYLON.StringDictionary();
  10193. }
  10194. return this._externalData.remove(key);
  10195. };
  10196. Engine.prototype.releaseInternalTexture = function (texture) {
  10197. if (!texture) {
  10198. return;
  10199. }
  10200. texture.references--;
  10201. // Final reference ?
  10202. if (texture.references === 0) {
  10203. var texturesCache = this.getLoadedTexturesCache();
  10204. var index = texturesCache.indexOf(texture);
  10205. if (index > -1) {
  10206. texturesCache.splice(index, 1);
  10207. }
  10208. this._releaseTexture(texture);
  10209. }
  10210. };
  10211. Engine.prototype.unbindAllAttributes = function () {
  10212. if (this._mustWipeVertexAttributes) {
  10213. this._mustWipeVertexAttributes = false;
  10214. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10215. this._gl.disableVertexAttribArray(i);
  10216. this._vertexAttribArraysEnabled[i] = false;
  10217. this._currentBufferPointers[i] = null;
  10218. }
  10219. return;
  10220. }
  10221. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10222. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10223. continue;
  10224. }
  10225. this._gl.disableVertexAttribArray(i);
  10226. this._vertexAttribArraysEnabled[i] = false;
  10227. this._currentBufferPointers[i] = null;
  10228. }
  10229. };
  10230. Engine.prototype.releaseEffects = function () {
  10231. for (var name in this._compiledEffects) {
  10232. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10233. }
  10234. this._compiledEffects = {};
  10235. };
  10236. // Dispose
  10237. Engine.prototype.dispose = function () {
  10238. this.hideLoadingUI();
  10239. this.stopRenderLoop();
  10240. // Empty texture
  10241. if (this._emptyTexture) {
  10242. this._releaseTexture(this._emptyTexture);
  10243. this._emptyTexture = null;
  10244. }
  10245. if (this._emptyCubeTexture) {
  10246. this._releaseTexture(this._emptyCubeTexture);
  10247. this._emptyCubeTexture = null;
  10248. }
  10249. // Release scenes
  10250. while (this.scenes.length) {
  10251. this.scenes[0].dispose();
  10252. }
  10253. // Release audio engine
  10254. if (Engine.audioEngine) {
  10255. Engine.audioEngine.dispose();
  10256. }
  10257. // Release effects
  10258. this.releaseEffects();
  10259. // Unbind
  10260. this.unbindAllAttributes();
  10261. this._gl = null;
  10262. //WebVR
  10263. this.disableVR();
  10264. // Events
  10265. window.removeEventListener("blur", this._onBlur);
  10266. window.removeEventListener("focus", this._onFocus);
  10267. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10268. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10269. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10270. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10271. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10272. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10273. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10274. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10275. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10276. // Remove from Instances
  10277. var index = Engine.Instances.indexOf(this);
  10278. if (index >= 0) {
  10279. Engine.Instances.splice(index, 1);
  10280. }
  10281. };
  10282. // Loading screen
  10283. Engine.prototype.displayLoadingUI = function () {
  10284. var loadingScreen = this.loadingScreen;
  10285. if (loadingScreen) {
  10286. loadingScreen.displayLoadingUI();
  10287. }
  10288. };
  10289. Engine.prototype.hideLoadingUI = function () {
  10290. var loadingScreen = this.loadingScreen;
  10291. if (loadingScreen) {
  10292. loadingScreen.hideLoadingUI();
  10293. }
  10294. };
  10295. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10296. get: function () {
  10297. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10298. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10299. return this._loadingScreen;
  10300. },
  10301. set: function (loadingScreen) {
  10302. this._loadingScreen = loadingScreen;
  10303. },
  10304. enumerable: true,
  10305. configurable: true
  10306. });
  10307. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10308. set: function (text) {
  10309. this.loadingScreen.loadingUIText = text;
  10310. },
  10311. enumerable: true,
  10312. configurable: true
  10313. });
  10314. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10315. set: function (color) {
  10316. this.loadingScreen.loadingUIBackgroundColor = color;
  10317. },
  10318. enumerable: true,
  10319. configurable: true
  10320. });
  10321. Engine.prototype.attachContextLostEvent = function (callback) {
  10322. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10323. };
  10324. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10325. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10326. };
  10327. Engine.prototype.getVertexShaderSource = function (program) {
  10328. var shaders = this._gl.getAttachedShaders(program);
  10329. return this._gl.getShaderSource(shaders[0]);
  10330. };
  10331. Engine.prototype.getFragmentShaderSource = function (program) {
  10332. var shaders = this._gl.getAttachedShaders(program);
  10333. return this._gl.getShaderSource(shaders[1]);
  10334. };
  10335. Engine.prototype.getError = function () {
  10336. return this._gl.getError();
  10337. };
  10338. // FPS
  10339. Engine.prototype.getFps = function () {
  10340. return this.fps;
  10341. };
  10342. Engine.prototype.getDeltaTime = function () {
  10343. return this.deltaTime;
  10344. };
  10345. Engine.prototype._measureFps = function () {
  10346. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10347. var length = this.previousFramesDuration.length;
  10348. if (length >= 2) {
  10349. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10350. }
  10351. if (length >= this.fpsRange) {
  10352. if (length > this.fpsRange) {
  10353. this.previousFramesDuration.splice(0, 1);
  10354. length = this.previousFramesDuration.length;
  10355. }
  10356. var sum = 0;
  10357. for (var id = 0; id < length - 1; id++) {
  10358. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10359. }
  10360. this.fps = 1000.0 / (sum / (length - 1));
  10361. }
  10362. };
  10363. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10364. if (this._webGLVersion > 1) {
  10365. return this._caps.colorBufferFloat;
  10366. }
  10367. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10368. };
  10369. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10370. if (this._webGLVersion > 1) {
  10371. return this._caps.colorBufferFloat;
  10372. }
  10373. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10374. };
  10375. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10376. Engine.prototype._canRenderToFramebuffer = function (type) {
  10377. var gl = this._gl;
  10378. //clear existing errors
  10379. while (gl.getError() !== gl.NO_ERROR) { }
  10380. var successful = true;
  10381. var texture = gl.createTexture();
  10382. gl.bindTexture(gl.TEXTURE_2D, texture);
  10383. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10384. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10385. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10386. var fb = gl.createFramebuffer();
  10387. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10388. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10389. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10390. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10391. successful = successful && (gl.getError() === gl.NO_ERROR);
  10392. //try render by clearing frame buffer's color buffer
  10393. if (successful) {
  10394. gl.clear(gl.COLOR_BUFFER_BIT);
  10395. successful = successful && (gl.getError() === gl.NO_ERROR);
  10396. }
  10397. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10398. if (successful) {
  10399. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10400. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10401. var readFormat = gl.RGBA;
  10402. var readType = gl.UNSIGNED_BYTE;
  10403. var buffer = new Uint8Array(4);
  10404. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10405. successful = successful && (gl.getError() === gl.NO_ERROR);
  10406. }
  10407. //clean up
  10408. gl.deleteTexture(texture);
  10409. gl.deleteFramebuffer(fb);
  10410. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10411. //clear accumulated errors
  10412. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10413. return successful;
  10414. };
  10415. Engine.prototype._getWebGLTextureType = function (type) {
  10416. if (type === Engine.TEXTURETYPE_FLOAT) {
  10417. return this._gl.FLOAT;
  10418. }
  10419. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10420. // Add Half Float Constant.
  10421. return Engine.HALF_FLOAT_OES;
  10422. }
  10423. return this._gl.UNSIGNED_BYTE;
  10424. };
  10425. ;
  10426. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10427. if (this._webGLVersion === 1) {
  10428. return this._gl.RGBA;
  10429. }
  10430. if (type === Engine.TEXTURETYPE_FLOAT) {
  10431. return Engine.RGBA32F;
  10432. }
  10433. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10434. return Engine.RGBA16F;
  10435. }
  10436. return this._gl.RGBA;
  10437. };
  10438. ;
  10439. // Statics
  10440. Engine.isSupported = function () {
  10441. try {
  10442. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10443. if (navigator.isCocoonJS) {
  10444. return true;
  10445. }
  10446. var tempcanvas = document.createElement("canvas");
  10447. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10448. return gl != null && !!window.WebGLRenderingContext;
  10449. }
  10450. catch (e) {
  10451. return false;
  10452. }
  10453. };
  10454. return Engine;
  10455. }());
  10456. Engine.Instances = new Array();
  10457. // Const statics
  10458. Engine._ALPHA_DISABLE = 0;
  10459. Engine._ALPHA_ADD = 1;
  10460. Engine._ALPHA_COMBINE = 2;
  10461. Engine._ALPHA_SUBTRACT = 3;
  10462. Engine._ALPHA_MULTIPLY = 4;
  10463. Engine._ALPHA_MAXIMIZED = 5;
  10464. Engine._ALPHA_ONEONE = 6;
  10465. Engine._ALPHA_PREMULTIPLIED = 7;
  10466. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10467. Engine._ALPHA_INTERPOLATE = 9;
  10468. Engine._ALPHA_SCREENMODE = 10;
  10469. Engine._DELAYLOADSTATE_NONE = 0;
  10470. Engine._DELAYLOADSTATE_LOADED = 1;
  10471. Engine._DELAYLOADSTATE_LOADING = 2;
  10472. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10473. Engine._TEXTUREFORMAT_ALPHA = 0;
  10474. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10475. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10476. Engine._TEXTUREFORMAT_RGB = 4;
  10477. Engine._TEXTUREFORMAT_RGBA = 5;
  10478. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10479. Engine._TEXTURETYPE_FLOAT = 1;
  10480. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10481. // Depht or Stencil test Constants.
  10482. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10483. 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.
  10484. 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.
  10485. 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.
  10486. 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.
  10487. 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.
  10488. 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.
  10489. 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.
  10490. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10491. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10492. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10493. // Stencil Actions Constants.
  10494. Engine._KEEP = 0x1E00;
  10495. Engine._REPLACE = 0x1E01;
  10496. Engine._INCR = 0x1E02;
  10497. Engine._DECR = 0x1E03;
  10498. Engine._INVERT = 0x150A;
  10499. Engine._INCR_WRAP = 0x8507;
  10500. Engine._DECR_WRAP = 0x8508;
  10501. // Texture rescaling mode
  10502. Engine._SCALEMODE_FLOOR = 1;
  10503. Engine._SCALEMODE_NEAREST = 2;
  10504. Engine._SCALEMODE_CEILING = 3;
  10505. // Updatable statics so stick with vars here
  10506. Engine.CollisionsEpsilon = 0.001;
  10507. Engine.CodeRepository = "src/";
  10508. Engine.ShadersRepository = "src/Shaders/";
  10509. BABYLON.Engine = Engine;
  10510. })(BABYLON || (BABYLON = {}));
  10511. //# sourceMappingURL=babylon.engine.js.map
  10512. /// <reference path="Tools\babylon.decorators.ts" />
  10513. var BABYLON;
  10514. (function (BABYLON) {
  10515. /**
  10516. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10517. */
  10518. var Node = (function () {
  10519. /**
  10520. * @constructor
  10521. * @param {string} name - the name and id to be given to this node
  10522. * @param {BABYLON.Scene} the scene this node will be added to
  10523. */
  10524. function Node(name, scene) {
  10525. this.state = "";
  10526. this.metadata = null;
  10527. this.doNotSerialize = false;
  10528. this.animations = new Array();
  10529. this._ranges = {};
  10530. this._childrenFlag = -1;
  10531. this._isEnabled = true;
  10532. this._isReady = true;
  10533. this._currentRenderId = -1;
  10534. this._parentRenderId = -1;
  10535. /**
  10536. * An event triggered when the mesh is disposed.
  10537. * @type {BABYLON.Observable}
  10538. */
  10539. this.onDisposeObservable = new BABYLON.Observable();
  10540. this.name = name;
  10541. this.id = name;
  10542. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10543. this._initCache();
  10544. }
  10545. Object.defineProperty(Node.prototype, "parent", {
  10546. get: function () {
  10547. return this._parentNode;
  10548. },
  10549. set: function (parent) {
  10550. if (this._parentNode === parent) {
  10551. return;
  10552. }
  10553. if (this._parentNode) {
  10554. var index = this._parentNode._children.indexOf(this);
  10555. if (index !== -1) {
  10556. this._parentNode._children.splice(index, 1);
  10557. }
  10558. }
  10559. this._parentNode = parent;
  10560. if (this._parentNode) {
  10561. if (!this._parentNode._children) {
  10562. this._parentNode._children = new Array();
  10563. }
  10564. this._parentNode._children.push(this);
  10565. }
  10566. },
  10567. enumerable: true,
  10568. configurable: true
  10569. });
  10570. Node.prototype.getClassName = function () {
  10571. return "Node";
  10572. };
  10573. Object.defineProperty(Node.prototype, "onDispose", {
  10574. set: function (callback) {
  10575. if (this._onDisposeObserver) {
  10576. this.onDisposeObservable.remove(this._onDisposeObserver);
  10577. }
  10578. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10579. },
  10580. enumerable: true,
  10581. configurable: true
  10582. });
  10583. Node.prototype.getScene = function () {
  10584. return this._scene;
  10585. };
  10586. Node.prototype.getEngine = function () {
  10587. return this._scene.getEngine();
  10588. };
  10589. // override it in derived class
  10590. Node.prototype.getWorldMatrix = function () {
  10591. return BABYLON.Matrix.Identity();
  10592. };
  10593. // override it in derived class if you add new variables to the cache
  10594. // and call the parent class method
  10595. Node.prototype._initCache = function () {
  10596. this._cache = {};
  10597. this._cache.parent = undefined;
  10598. };
  10599. Node.prototype.updateCache = function (force) {
  10600. if (!force && this.isSynchronized())
  10601. return;
  10602. this._cache.parent = this.parent;
  10603. this._updateCache();
  10604. };
  10605. // override it in derived class if you add new variables to the cache
  10606. // and call the parent class method if !ignoreParentClass
  10607. Node.prototype._updateCache = function (ignoreParentClass) {
  10608. };
  10609. // override it in derived class if you add new variables to the cache
  10610. Node.prototype._isSynchronized = function () {
  10611. return true;
  10612. };
  10613. Node.prototype._markSyncedWithParent = function () {
  10614. this._parentRenderId = this.parent._currentRenderId;
  10615. };
  10616. Node.prototype.isSynchronizedWithParent = function () {
  10617. if (!this.parent) {
  10618. return true;
  10619. }
  10620. if (this._parentRenderId !== this.parent._currentRenderId) {
  10621. return false;
  10622. }
  10623. return this.parent.isSynchronized();
  10624. };
  10625. Node.prototype.isSynchronized = function (updateCache) {
  10626. var check = this.hasNewParent();
  10627. check = check || !this.isSynchronizedWithParent();
  10628. check = check || !this._isSynchronized();
  10629. if (updateCache)
  10630. this.updateCache(true);
  10631. return !check;
  10632. };
  10633. Node.prototype.hasNewParent = function (update) {
  10634. if (this._cache.parent === this.parent)
  10635. return false;
  10636. if (update)
  10637. this._cache.parent = this.parent;
  10638. return true;
  10639. };
  10640. /**
  10641. * Is this node ready to be used/rendered
  10642. * @return {boolean} is it ready
  10643. */
  10644. Node.prototype.isReady = function () {
  10645. return this._isReady;
  10646. };
  10647. /**
  10648. * Is this node enabled.
  10649. * If the node has a parent and is enabled, the parent will be inspected as well.
  10650. * @return {boolean} whether this node (and its parent) is enabled.
  10651. * @see setEnabled
  10652. */
  10653. Node.prototype.isEnabled = function () {
  10654. if (!this._isEnabled) {
  10655. return false;
  10656. }
  10657. if (this.parent) {
  10658. return this.parent.isEnabled();
  10659. }
  10660. return true;
  10661. };
  10662. /**
  10663. * Set the enabled state of this node.
  10664. * @param {boolean} value - the new enabled state
  10665. * @see isEnabled
  10666. */
  10667. Node.prototype.setEnabled = function (value) {
  10668. this._isEnabled = value;
  10669. };
  10670. /**
  10671. * Is this node a descendant of the given node.
  10672. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10673. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10674. * @see parent
  10675. */
  10676. Node.prototype.isDescendantOf = function (ancestor) {
  10677. if (this.parent) {
  10678. if (this.parent === ancestor) {
  10679. return true;
  10680. }
  10681. return this.parent.isDescendantOf(ancestor);
  10682. }
  10683. return false;
  10684. };
  10685. /**
  10686. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10687. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10688. * @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.
  10689. * @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.
  10690. */
  10691. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10692. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10693. if (!this._children) {
  10694. return;
  10695. }
  10696. for (var index = 0; index < this._children.length; index++) {
  10697. var item = this._children[index];
  10698. if (!predicate || predicate(item)) {
  10699. results.push(item);
  10700. }
  10701. if (!directDescendantsOnly) {
  10702. item._getDescendants(results, false, predicate);
  10703. }
  10704. }
  10705. };
  10706. /**
  10707. * Will return all nodes that have this node as ascendant.
  10708. * @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.
  10709. * @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.
  10710. * @return {BABYLON.Node[]} all children nodes of all types.
  10711. */
  10712. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10713. var results = [];
  10714. this._getDescendants(results, directDescendantsOnly, predicate);
  10715. return results;
  10716. };
  10717. /**
  10718. * Get all child-meshes of this node.
  10719. */
  10720. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10721. var results = [];
  10722. this._getDescendants(results, directDecendantsOnly, function (node) {
  10723. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10724. });
  10725. return results;
  10726. };
  10727. /**
  10728. * Get all direct children of this node.
  10729. */
  10730. Node.prototype.getChildren = function (predicate) {
  10731. return this.getDescendants(true, predicate);
  10732. };
  10733. Node.prototype._setReady = function (state) {
  10734. if (state === this._isReady) {
  10735. return;
  10736. }
  10737. if (!state) {
  10738. this._isReady = false;
  10739. return;
  10740. }
  10741. this._isReady = true;
  10742. if (this.onReady) {
  10743. this.onReady(this);
  10744. }
  10745. };
  10746. Node.prototype.getAnimationByName = function (name) {
  10747. for (var i = 0; i < this.animations.length; i++) {
  10748. var animation = this.animations[i];
  10749. if (animation.name === name) {
  10750. return animation;
  10751. }
  10752. }
  10753. return null;
  10754. };
  10755. Node.prototype.createAnimationRange = function (name, from, to) {
  10756. // check name not already in use
  10757. if (!this._ranges[name]) {
  10758. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10759. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10760. if (this.animations[i]) {
  10761. this.animations[i].createRange(name, from, to);
  10762. }
  10763. }
  10764. }
  10765. };
  10766. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10767. if (deleteFrames === void 0) { deleteFrames = true; }
  10768. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10769. if (this.animations[i]) {
  10770. this.animations[i].deleteRange(name, deleteFrames);
  10771. }
  10772. }
  10773. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10774. };
  10775. Node.prototype.getAnimationRange = function (name) {
  10776. return this._ranges[name];
  10777. };
  10778. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10779. var range = this.getAnimationRange(name);
  10780. if (!range) {
  10781. return null;
  10782. }
  10783. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10784. };
  10785. Node.prototype.serializeAnimationRanges = function () {
  10786. var serializationRanges = [];
  10787. for (var name in this._ranges) {
  10788. var range = {};
  10789. range.name = name;
  10790. range.from = this._ranges[name].from;
  10791. range.to = this._ranges[name].to;
  10792. serializationRanges.push(range);
  10793. }
  10794. return serializationRanges;
  10795. };
  10796. Node.prototype.dispose = function () {
  10797. this.parent = null;
  10798. // Callback
  10799. this.onDisposeObservable.notifyObservers(this);
  10800. this.onDisposeObservable.clear();
  10801. };
  10802. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10803. if (parsedNode.ranges) {
  10804. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10805. var data = parsedNode.ranges[index];
  10806. node.createAnimationRange(data.name, data.from, data.to);
  10807. }
  10808. }
  10809. };
  10810. return Node;
  10811. }());
  10812. __decorate([
  10813. BABYLON.serialize()
  10814. ], Node.prototype, "name", void 0);
  10815. __decorate([
  10816. BABYLON.serialize()
  10817. ], Node.prototype, "id", void 0);
  10818. __decorate([
  10819. BABYLON.serialize()
  10820. ], Node.prototype, "uniqueId", void 0);
  10821. __decorate([
  10822. BABYLON.serialize()
  10823. ], Node.prototype, "state", void 0);
  10824. __decorate([
  10825. BABYLON.serialize()
  10826. ], Node.prototype, "metadata", void 0);
  10827. BABYLON.Node = Node;
  10828. })(BABYLON || (BABYLON = {}));
  10829. //# sourceMappingURL=babylon.node.js.map
  10830. var BABYLON;
  10831. (function (BABYLON) {
  10832. var BoundingSphere = (function () {
  10833. function BoundingSphere(minimum, maximum) {
  10834. this.minimum = minimum;
  10835. this.maximum = maximum;
  10836. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10837. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10838. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10839. this.radius = distance * 0.5;
  10840. this.centerWorld = BABYLON.Vector3.Zero();
  10841. this._update(BABYLON.Matrix.Identity());
  10842. }
  10843. // Methods
  10844. BoundingSphere.prototype._update = function (world) {
  10845. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10846. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10847. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10848. };
  10849. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10850. for (var i = 0; i < 6; i++) {
  10851. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10852. return false;
  10853. }
  10854. return true;
  10855. };
  10856. BoundingSphere.prototype.intersectsPoint = function (point) {
  10857. var x = this.centerWorld.x - point.x;
  10858. var y = this.centerWorld.y - point.y;
  10859. var z = this.centerWorld.z - point.z;
  10860. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10861. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10862. return false;
  10863. return true;
  10864. };
  10865. // Statics
  10866. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10867. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10868. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10869. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10870. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10871. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10872. return false;
  10873. return true;
  10874. };
  10875. return BoundingSphere;
  10876. }());
  10877. BABYLON.BoundingSphere = BoundingSphere;
  10878. })(BABYLON || (BABYLON = {}));
  10879. //# sourceMappingURL=babylon.boundingSphere.js.map
  10880. var BABYLON;
  10881. (function (BABYLON) {
  10882. var BoundingBox = (function () {
  10883. function BoundingBox(minimum, maximum) {
  10884. this.minimum = minimum;
  10885. this.maximum = maximum;
  10886. this.vectors = new Array();
  10887. this.vectorsWorld = new Array();
  10888. // Bounding vectors
  10889. this.vectors.push(this.minimum.clone());
  10890. this.vectors.push(this.maximum.clone());
  10891. this.vectors.push(this.minimum.clone());
  10892. this.vectors[2].x = this.maximum.x;
  10893. this.vectors.push(this.minimum.clone());
  10894. this.vectors[3].y = this.maximum.y;
  10895. this.vectors.push(this.minimum.clone());
  10896. this.vectors[4].z = this.maximum.z;
  10897. this.vectors.push(this.maximum.clone());
  10898. this.vectors[5].z = this.minimum.z;
  10899. this.vectors.push(this.maximum.clone());
  10900. this.vectors[6].x = this.minimum.x;
  10901. this.vectors.push(this.maximum.clone());
  10902. this.vectors[7].y = this.minimum.y;
  10903. // OBB
  10904. this.center = this.maximum.add(this.minimum).scale(0.5);
  10905. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10906. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10907. // World
  10908. for (var index = 0; index < this.vectors.length; index++) {
  10909. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10910. }
  10911. this.minimumWorld = BABYLON.Vector3.Zero();
  10912. this.maximumWorld = BABYLON.Vector3.Zero();
  10913. this.centerWorld = BABYLON.Vector3.Zero();
  10914. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10915. this._update(BABYLON.Matrix.Identity());
  10916. }
  10917. // Methods
  10918. BoundingBox.prototype.getWorldMatrix = function () {
  10919. return this._worldMatrix;
  10920. };
  10921. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10922. this._worldMatrix.copyFrom(matrix);
  10923. return this;
  10924. };
  10925. BoundingBox.prototype._update = function (world) {
  10926. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10927. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10928. for (var index = 0; index < this.vectors.length; index++) {
  10929. var v = this.vectorsWorld[index];
  10930. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10931. if (v.x < this.minimumWorld.x)
  10932. this.minimumWorld.x = v.x;
  10933. if (v.y < this.minimumWorld.y)
  10934. this.minimumWorld.y = v.y;
  10935. if (v.z < this.minimumWorld.z)
  10936. this.minimumWorld.z = v.z;
  10937. if (v.x > this.maximumWorld.x)
  10938. this.maximumWorld.x = v.x;
  10939. if (v.y > this.maximumWorld.y)
  10940. this.maximumWorld.y = v.y;
  10941. if (v.z > this.maximumWorld.z)
  10942. this.maximumWorld.z = v.z;
  10943. }
  10944. // Extend
  10945. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10946. this.extendSizeWorld.scaleInPlace(0.5);
  10947. // OBB
  10948. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10949. this.centerWorld.scaleInPlace(0.5);
  10950. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10951. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10952. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10953. this._worldMatrix = world;
  10954. };
  10955. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10956. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10957. };
  10958. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10959. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10960. };
  10961. BoundingBox.prototype.intersectsPoint = function (point) {
  10962. var delta = -BABYLON.Epsilon;
  10963. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10964. return false;
  10965. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10966. return false;
  10967. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10968. return false;
  10969. return true;
  10970. };
  10971. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10972. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10973. };
  10974. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10975. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10976. return false;
  10977. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10978. return false;
  10979. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10980. return false;
  10981. return true;
  10982. };
  10983. // Statics
  10984. BoundingBox.Intersects = function (box0, box1) {
  10985. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10986. return false;
  10987. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10988. return false;
  10989. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10990. return false;
  10991. return true;
  10992. };
  10993. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10994. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10995. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10996. return (num <= (sphereRadius * sphereRadius));
  10997. };
  10998. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10999. for (var p = 0; p < 6; p++) {
  11000. for (var i = 0; i < 8; i++) {
  11001. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11002. return false;
  11003. }
  11004. }
  11005. }
  11006. return true;
  11007. };
  11008. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11009. for (var p = 0; p < 6; p++) {
  11010. var inCount = 8;
  11011. for (var i = 0; i < 8; i++) {
  11012. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11013. --inCount;
  11014. }
  11015. else {
  11016. break;
  11017. }
  11018. }
  11019. if (inCount === 0)
  11020. return false;
  11021. }
  11022. return true;
  11023. };
  11024. return BoundingBox;
  11025. }());
  11026. BABYLON.BoundingBox = BoundingBox;
  11027. })(BABYLON || (BABYLON = {}));
  11028. //# sourceMappingURL=babylon.boundingBox.js.map
  11029. var BABYLON;
  11030. (function (BABYLON) {
  11031. var computeBoxExtents = function (axis, box) {
  11032. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11033. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11034. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11035. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11036. var r = r0 + r1 + r2;
  11037. return {
  11038. min: p - r,
  11039. max: p + r
  11040. };
  11041. };
  11042. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11043. var axisOverlap = function (axis, box0, box1) {
  11044. var result0 = computeBoxExtents(axis, box0);
  11045. var result1 = computeBoxExtents(axis, box1);
  11046. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11047. };
  11048. var BoundingInfo = (function () {
  11049. function BoundingInfo(minimum, maximum) {
  11050. this.minimum = minimum;
  11051. this.maximum = maximum;
  11052. this._isLocked = false;
  11053. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11054. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11055. }
  11056. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11057. get: function () {
  11058. return this._isLocked;
  11059. },
  11060. set: function (value) {
  11061. this._isLocked = value;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. // Methods
  11067. BoundingInfo.prototype.update = function (world) {
  11068. if (this._isLocked) {
  11069. return;
  11070. }
  11071. this.boundingBox._update(world);
  11072. this.boundingSphere._update(world);
  11073. };
  11074. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11075. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11076. return false;
  11077. return this.boundingBox.isInFrustum(frustumPlanes);
  11078. };
  11079. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11080. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11081. };
  11082. BoundingInfo.prototype._checkCollision = function (collider) {
  11083. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11084. };
  11085. BoundingInfo.prototype.intersectsPoint = function (point) {
  11086. if (!this.boundingSphere.centerWorld) {
  11087. return false;
  11088. }
  11089. if (!this.boundingSphere.intersectsPoint(point)) {
  11090. return false;
  11091. }
  11092. if (!this.boundingBox.intersectsPoint(point)) {
  11093. return false;
  11094. }
  11095. return true;
  11096. };
  11097. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11098. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11099. return false;
  11100. }
  11101. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11102. return false;
  11103. }
  11104. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11105. return false;
  11106. }
  11107. if (!precise) {
  11108. return true;
  11109. }
  11110. var box0 = this.boundingBox;
  11111. var box1 = boundingInfo.boundingBox;
  11112. if (!axisOverlap(box0.directions[0], box0, box1))
  11113. return false;
  11114. if (!axisOverlap(box0.directions[1], box0, box1))
  11115. return false;
  11116. if (!axisOverlap(box0.directions[2], box0, box1))
  11117. return false;
  11118. if (!axisOverlap(box1.directions[0], box0, box1))
  11119. return false;
  11120. if (!axisOverlap(box1.directions[1], box0, box1))
  11121. return false;
  11122. if (!axisOverlap(box1.directions[2], box0, box1))
  11123. return false;
  11124. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11125. return false;
  11126. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11127. return false;
  11128. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11129. return false;
  11130. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11131. return false;
  11132. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11133. return false;
  11134. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11135. return false;
  11136. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11137. return false;
  11138. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11139. return false;
  11140. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11141. return false;
  11142. return true;
  11143. };
  11144. return BoundingInfo;
  11145. }());
  11146. BABYLON.BoundingInfo = BoundingInfo;
  11147. })(BABYLON || (BABYLON = {}));
  11148. //# sourceMappingURL=babylon.boundingInfo.js.map
  11149. var BABYLON;
  11150. (function (BABYLON) {
  11151. var AbstractMesh = (function (_super) {
  11152. __extends(AbstractMesh, _super);
  11153. // Constructor
  11154. function AbstractMesh(name, scene) {
  11155. var _this = _super.call(this, name, scene) || this;
  11156. _this._facetNb = 0; // facet number
  11157. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11158. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11159. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11160. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11161. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11162. _this._subDiv = {
  11163. max: 1,
  11164. X: 1,
  11165. Y: 1,
  11166. Z: 1
  11167. };
  11168. // Events
  11169. /**
  11170. * An event triggered when this mesh collides with another one
  11171. * @type {BABYLON.Observable}
  11172. */
  11173. _this.onCollideObservable = new BABYLON.Observable();
  11174. /**
  11175. * An event triggered when the collision's position changes
  11176. * @type {BABYLON.Observable}
  11177. */
  11178. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11179. /**
  11180. * An event triggered after the world matrix is updated
  11181. * @type {BABYLON.Observable}
  11182. */
  11183. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11184. // Properties
  11185. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11186. _this.position = BABYLON.Vector3.Zero();
  11187. _this._rotation = BABYLON.Vector3.Zero();
  11188. _this._scaling = BABYLON.Vector3.One();
  11189. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11190. _this.visibility = 1.0;
  11191. _this.alphaIndex = Number.MAX_VALUE;
  11192. _this.infiniteDistance = false;
  11193. _this.isVisible = true;
  11194. _this.isPickable = true;
  11195. _this.showBoundingBox = false;
  11196. _this.showSubMeshesBoundingBox = false;
  11197. _this.isBlocker = false;
  11198. _this.renderingGroupId = 0;
  11199. _this._receiveShadows = false;
  11200. _this.renderOutline = false;
  11201. _this.outlineColor = BABYLON.Color3.Red();
  11202. _this.outlineWidth = 0.02;
  11203. _this.renderOverlay = false;
  11204. _this.overlayColor = BABYLON.Color3.Red();
  11205. _this.overlayAlpha = 0.5;
  11206. _this._hasVertexAlpha = false;
  11207. _this._useVertexColors = true;
  11208. _this._computeBonesUsingShaders = true;
  11209. _this._numBoneInfluencers = 4;
  11210. _this._applyFog = true;
  11211. _this.scalingDeterminant = 1;
  11212. _this.useOctreeForRenderingSelection = true;
  11213. _this.useOctreeForPicking = true;
  11214. _this.useOctreeForCollisions = true;
  11215. _this.layerMask = 0x0FFFFFFF;
  11216. /**
  11217. * True if the mesh must be rendered in any case.
  11218. */
  11219. _this.alwaysSelectAsActiveMesh = false;
  11220. // Collisions
  11221. _this._checkCollisions = false;
  11222. _this._collisionMask = -1;
  11223. _this._collisionGroup = -1;
  11224. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11225. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11226. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11227. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11228. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11229. // Edges
  11230. _this.edgesWidth = 1;
  11231. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11232. // Cache
  11233. _this._localWorld = BABYLON.Matrix.Zero();
  11234. _this._worldMatrix = BABYLON.Matrix.Zero();
  11235. _this._absolutePosition = BABYLON.Vector3.Zero();
  11236. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11237. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11238. _this._isDirty = false;
  11239. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11240. _this._isDisposed = false;
  11241. _this._renderId = 0;
  11242. _this._intersectionsInProgress = new Array();
  11243. _this._isWorldMatrixFrozen = false;
  11244. _this._unIndexed = false;
  11245. _this._lightSources = new Array();
  11246. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11247. if (collidedMesh === void 0) { collidedMesh = null; }
  11248. //TODO move this to the collision coordinator!
  11249. if (_this.getScene().workerCollisions)
  11250. newPosition.multiplyInPlace(_this._collider.radius);
  11251. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11252. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11253. _this.position.addInPlace(_this._diffPositionForCollisions);
  11254. }
  11255. if (collidedMesh) {
  11256. _this.onCollideObservable.notifyObservers(collidedMesh);
  11257. }
  11258. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11259. };
  11260. _this.getScene().addMesh(_this);
  11261. _this._resyncLightSources();
  11262. return _this;
  11263. }
  11264. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11265. get: function () {
  11266. return AbstractMesh._BILLBOARDMODE_NONE;
  11267. },
  11268. enumerable: true,
  11269. configurable: true
  11270. });
  11271. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11272. get: function () {
  11273. return AbstractMesh._BILLBOARDMODE_X;
  11274. },
  11275. enumerable: true,
  11276. configurable: true
  11277. });
  11278. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11279. get: function () {
  11280. return AbstractMesh._BILLBOARDMODE_Y;
  11281. },
  11282. enumerable: true,
  11283. configurable: true
  11284. });
  11285. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11286. get: function () {
  11287. return AbstractMesh._BILLBOARDMODE_Z;
  11288. },
  11289. enumerable: true,
  11290. configurable: true
  11291. });
  11292. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11293. get: function () {
  11294. return AbstractMesh._BILLBOARDMODE_ALL;
  11295. },
  11296. enumerable: true,
  11297. configurable: true
  11298. });
  11299. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11300. /**
  11301. * Read-only : the number of facets in the mesh
  11302. */
  11303. get: function () {
  11304. return this._facetNb;
  11305. },
  11306. enumerable: true,
  11307. configurable: true
  11308. });
  11309. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11310. /**
  11311. * The number (integer) of subdivisions per axis in the partioning space
  11312. */
  11313. get: function () {
  11314. return this._partitioningSubdivisions;
  11315. },
  11316. set: function (nb) {
  11317. this._partitioningSubdivisions = nb;
  11318. },
  11319. enumerable: true,
  11320. configurable: true
  11321. });
  11322. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11323. /**
  11324. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11325. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11326. */
  11327. get: function () {
  11328. return this._partitioningBBoxRatio;
  11329. },
  11330. set: function (ratio) {
  11331. this._partitioningBBoxRatio = ratio;
  11332. },
  11333. enumerable: true,
  11334. configurable: true
  11335. });
  11336. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11337. /**
  11338. * Read-only boolean : is the feature facetData enabled ?
  11339. */
  11340. get: function () {
  11341. return this._facetDataEnabled;
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11347. set: function (callback) {
  11348. if (this._onCollideObserver) {
  11349. this.onCollideObservable.remove(this._onCollideObserver);
  11350. }
  11351. this._onCollideObserver = this.onCollideObservable.add(callback);
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11357. set: function (callback) {
  11358. if (this._onCollisionPositionChangeObserver) {
  11359. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11360. }
  11361. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11362. },
  11363. enumerable: true,
  11364. configurable: true
  11365. });
  11366. Object.defineProperty(AbstractMesh.prototype, "material", {
  11367. get: function () {
  11368. return this._material;
  11369. },
  11370. set: function (value) {
  11371. if (this._material === value) {
  11372. return;
  11373. }
  11374. this._material = value;
  11375. if (!this.subMeshes) {
  11376. return;
  11377. }
  11378. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11379. var subMesh = _a[_i];
  11380. subMesh.setEffect(null);
  11381. }
  11382. },
  11383. enumerable: true,
  11384. configurable: true
  11385. });
  11386. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11387. get: function () {
  11388. return this._receiveShadows;
  11389. },
  11390. set: function (value) {
  11391. if (this._receiveShadows === value) {
  11392. return;
  11393. }
  11394. this._receiveShadows = value;
  11395. this._markSubMeshesAsLightDirty();
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11401. get: function () {
  11402. return this._hasVertexAlpha;
  11403. },
  11404. set: function (value) {
  11405. if (this._hasVertexAlpha === value) {
  11406. return;
  11407. }
  11408. this._hasVertexAlpha = value;
  11409. this._markSubMeshesAsAttributesDirty();
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11415. get: function () {
  11416. return this._useVertexColors;
  11417. },
  11418. set: function (value) {
  11419. if (this._useVertexColors === value) {
  11420. return;
  11421. }
  11422. this._useVertexColors = value;
  11423. this._markSubMeshesAsAttributesDirty();
  11424. },
  11425. enumerable: true,
  11426. configurable: true
  11427. });
  11428. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11429. get: function () {
  11430. return this._computeBonesUsingShaders;
  11431. },
  11432. set: function (value) {
  11433. if (this._computeBonesUsingShaders === value) {
  11434. return;
  11435. }
  11436. this._computeBonesUsingShaders = value;
  11437. this._markSubMeshesAsAttributesDirty();
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11443. get: function () {
  11444. return this._numBoneInfluencers;
  11445. },
  11446. set: function (value) {
  11447. if (this._numBoneInfluencers === value) {
  11448. return;
  11449. }
  11450. this._numBoneInfluencers = value;
  11451. this._markSubMeshesAsAttributesDirty();
  11452. },
  11453. enumerable: true,
  11454. configurable: true
  11455. });
  11456. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11457. get: function () {
  11458. return this._applyFog;
  11459. },
  11460. set: function (value) {
  11461. if (this._applyFog === value) {
  11462. return;
  11463. }
  11464. this._applyFog = value;
  11465. this._markSubMeshesAsMiscDirty();
  11466. },
  11467. enumerable: true,
  11468. configurable: true
  11469. });
  11470. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11471. get: function () {
  11472. return this._collisionMask;
  11473. },
  11474. set: function (mask) {
  11475. this._collisionMask = !isNaN(mask) ? mask : -1;
  11476. },
  11477. enumerable: true,
  11478. configurable: true
  11479. });
  11480. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11481. get: function () {
  11482. return this._collisionGroup;
  11483. },
  11484. set: function (mask) {
  11485. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11491. get: function () {
  11492. return null;
  11493. },
  11494. enumerable: true,
  11495. configurable: true
  11496. });
  11497. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11498. get: function () {
  11499. return this._skeleton;
  11500. },
  11501. set: function (value) {
  11502. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11503. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11504. }
  11505. if (value && value.needInitialSkinMatrix) {
  11506. value._registerMeshWithPoseMatrix(this);
  11507. }
  11508. this._skeleton = value;
  11509. if (!this._skeleton) {
  11510. this._bonesTransformMatrices = null;
  11511. }
  11512. this._markSubMeshesAsAttributesDirty();
  11513. },
  11514. enumerable: true,
  11515. configurable: true
  11516. });
  11517. /**
  11518. * Returns the string "AbstractMesh"
  11519. */
  11520. AbstractMesh.prototype.getClassName = function () {
  11521. return "AbstractMesh";
  11522. };
  11523. /**
  11524. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11525. */
  11526. AbstractMesh.prototype.toString = function (fullDetails) {
  11527. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11528. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11529. if (this._skeleton) {
  11530. ret += ", skeleton: " + this._skeleton.name;
  11531. }
  11532. if (fullDetails) {
  11533. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11534. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11535. }
  11536. return ret;
  11537. };
  11538. AbstractMesh.prototype._resyncLightSources = function () {
  11539. this._lightSources.length = 0;
  11540. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11541. var light = _a[_i];
  11542. if (!light.isEnabled()) {
  11543. continue;
  11544. }
  11545. if (light.canAffectMesh(this)) {
  11546. this._lightSources.push(light);
  11547. }
  11548. }
  11549. this._markSubMeshesAsLightDirty();
  11550. };
  11551. AbstractMesh.prototype._resyncLighSource = function (light) {
  11552. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11553. var index = this._lightSources.indexOf(light);
  11554. if (index === -1) {
  11555. if (!isIn) {
  11556. return;
  11557. }
  11558. this._lightSources.push(light);
  11559. }
  11560. else {
  11561. if (isIn) {
  11562. return;
  11563. }
  11564. this._lightSources.splice(index, 1);
  11565. }
  11566. this._markSubMeshesAsLightDirty();
  11567. };
  11568. AbstractMesh.prototype._removeLightSource = function (light) {
  11569. var index = this._lightSources.indexOf(light);
  11570. if (index === -1) {
  11571. return;
  11572. }
  11573. this._lightSources.splice(index, 1);
  11574. };
  11575. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11576. if (!this.subMeshes) {
  11577. return;
  11578. }
  11579. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11580. var subMesh = _a[_i];
  11581. if (subMesh._materialDefines) {
  11582. func(subMesh._materialDefines);
  11583. }
  11584. }
  11585. };
  11586. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11587. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11588. };
  11589. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11590. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11591. };
  11592. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11593. if (!this.subMeshes) {
  11594. return;
  11595. }
  11596. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11597. var subMesh = _a[_i];
  11598. var material = subMesh.getMaterial();
  11599. if (material) {
  11600. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11601. }
  11602. }
  11603. };
  11604. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11605. /**
  11606. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11607. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11608. * Default : (0.0, 0.0, 0.0)
  11609. */
  11610. get: function () {
  11611. return this._rotation;
  11612. },
  11613. set: function (newRotation) {
  11614. this._rotation = newRotation;
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11620. /**
  11621. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11622. * Default : (1.0, 1.0, 1.0)
  11623. */
  11624. get: function () {
  11625. return this._scaling;
  11626. },
  11627. set: function (newScaling) {
  11628. this._scaling = newScaling;
  11629. if (this.physicsImpostor) {
  11630. this.physicsImpostor.forceUpdate();
  11631. }
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11637. /**
  11638. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11639. * It's null by default.
  11640. * 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)
  11641. */
  11642. get: function () {
  11643. return this._rotationQuaternion;
  11644. },
  11645. set: function (quaternion) {
  11646. this._rotationQuaternion = quaternion;
  11647. //reset the rotation vector.
  11648. if (quaternion && this.rotation.length()) {
  11649. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11650. }
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. // Methods
  11656. /**
  11657. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11658. * Returns the AbstractMesh.
  11659. */
  11660. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11661. this._poseMatrix.copyFrom(matrix);
  11662. return this;
  11663. };
  11664. /**
  11665. * Returns the mesh Pose matrix.
  11666. * Returned object : Matrix
  11667. */
  11668. AbstractMesh.prototype.getPoseMatrix = function () {
  11669. return this._poseMatrix;
  11670. };
  11671. /**
  11672. * Disables the mesh edger rendering mode.
  11673. * Returns the AbstractMesh.
  11674. */
  11675. AbstractMesh.prototype.disableEdgesRendering = function () {
  11676. if (this._edgesRenderer !== undefined) {
  11677. this._edgesRenderer.dispose();
  11678. this._edgesRenderer = undefined;
  11679. }
  11680. return this;
  11681. };
  11682. /**
  11683. * Enables the edge rendering mode on the mesh.
  11684. * This mode makes the mesh edges visible.
  11685. * Returns the AbstractMesh.
  11686. */
  11687. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11688. if (epsilon === void 0) { epsilon = 0.95; }
  11689. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11690. this.disableEdgesRendering();
  11691. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11692. return this;
  11693. };
  11694. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11695. /**
  11696. * Returns true if the mesh is blocked. Used by the class Mesh.
  11697. * Returns the boolean `false` by default.
  11698. */
  11699. get: function () {
  11700. return false;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. /**
  11706. * Returns the mesh itself by default, used by the class Mesh.
  11707. * Returned type : AbstractMesh
  11708. */
  11709. AbstractMesh.prototype.getLOD = function (camera) {
  11710. return this;
  11711. };
  11712. /**
  11713. * Returns 0 by default, used by the class Mesh.
  11714. * Returns an integer.
  11715. */
  11716. AbstractMesh.prototype.getTotalVertices = function () {
  11717. return 0;
  11718. };
  11719. /**
  11720. * Returns null by default, used by the class Mesh.
  11721. * Returned type : integer array
  11722. */
  11723. AbstractMesh.prototype.getIndices = function () {
  11724. return null;
  11725. };
  11726. /**
  11727. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11728. * Returned type : float array or Float32Array
  11729. */
  11730. AbstractMesh.prototype.getVerticesData = function (kind) {
  11731. return null;
  11732. };
  11733. /**
  11734. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11735. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11736. * The `data` are either a numeric array either a Float32Array.
  11737. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11738. * 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).
  11739. * Note that a new underlying VertexBuffer object is created each call.
  11740. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11741. *
  11742. * Possible `kind` values :
  11743. * - BABYLON.VertexBuffer.PositionKind
  11744. * - BABYLON.VertexBuffer.UVKind
  11745. * - BABYLON.VertexBuffer.UV2Kind
  11746. * - BABYLON.VertexBuffer.UV3Kind
  11747. * - BABYLON.VertexBuffer.UV4Kind
  11748. * - BABYLON.VertexBuffer.UV5Kind
  11749. * - BABYLON.VertexBuffer.UV6Kind
  11750. * - BABYLON.VertexBuffer.ColorKind
  11751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11755. *
  11756. * Returns the Mesh.
  11757. */
  11758. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11759. return null;
  11760. };
  11761. /**
  11762. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11763. * If the mesh has no geometry, it is simply returned as it is.
  11764. * The `data` are either a numeric array either a Float32Array.
  11765. * No new underlying VertexBuffer object is created.
  11766. * 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.
  11767. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11768. *
  11769. * Possible `kind` values :
  11770. * - BABYLON.VertexBuffer.PositionKind
  11771. * - BABYLON.VertexBuffer.UVKind
  11772. * - BABYLON.VertexBuffer.UV2Kind
  11773. * - BABYLON.VertexBuffer.UV3Kind
  11774. * - BABYLON.VertexBuffer.UV4Kind
  11775. * - BABYLON.VertexBuffer.UV5Kind
  11776. * - BABYLON.VertexBuffer.UV6Kind
  11777. * - BABYLON.VertexBuffer.ColorKind
  11778. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11779. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11780. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11781. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11782. *
  11783. * Returns the Mesh.
  11784. */
  11785. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11786. return null;
  11787. };
  11788. /**
  11789. * Sets the mesh indices.
  11790. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11791. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11792. * This method creates a new index buffer each call.
  11793. * Returns the Mesh.
  11794. */
  11795. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11796. return null;
  11797. };
  11798. /** Returns false by default, used by the class Mesh.
  11799. * Returns a boolean
  11800. */
  11801. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11802. return false;
  11803. };
  11804. /**
  11805. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11806. * Returns a BoundingInfo
  11807. */
  11808. AbstractMesh.prototype.getBoundingInfo = function () {
  11809. if (this._masterMesh) {
  11810. return this._masterMesh.getBoundingInfo();
  11811. }
  11812. if (!this._boundingInfo) {
  11813. this._updateBoundingInfo();
  11814. }
  11815. return this._boundingInfo;
  11816. };
  11817. /**
  11818. * Sets a mesh new object BoundingInfo.
  11819. * Returns the AbstractMesh.
  11820. */
  11821. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11822. this._boundingInfo = boundingInfo;
  11823. return this;
  11824. };
  11825. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11826. get: function () {
  11827. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. AbstractMesh.prototype._preActivate = function () {
  11833. };
  11834. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11835. };
  11836. AbstractMesh.prototype._activate = function (renderId) {
  11837. this._renderId = renderId;
  11838. };
  11839. /**
  11840. * Returns the last update of the World matrix
  11841. * Returns a Matrix.
  11842. */
  11843. AbstractMesh.prototype.getWorldMatrix = function () {
  11844. if (this._masterMesh) {
  11845. return this._masterMesh.getWorldMatrix();
  11846. }
  11847. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11848. this.computeWorldMatrix();
  11849. }
  11850. return this._worldMatrix;
  11851. };
  11852. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11853. /**
  11854. * Returns directly the last state of the mesh World matrix.
  11855. * A Matrix is returned.
  11856. */
  11857. get: function () {
  11858. return this._worldMatrix;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11864. /**
  11865. * Returns the current mesh absolute position.
  11866. * Retuns a Vector3.
  11867. */
  11868. get: function () {
  11869. return this._absolutePosition;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. /**
  11875. * Prevents the World matrix to be computed any longer.
  11876. * Returns the AbstractMesh.
  11877. */
  11878. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11879. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11880. this.computeWorldMatrix(true);
  11881. this._isWorldMatrixFrozen = true;
  11882. return this;
  11883. };
  11884. /**
  11885. * Allows back the World matrix computation.
  11886. * Returns the AbstractMesh.
  11887. */
  11888. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11889. this._isWorldMatrixFrozen = false;
  11890. this.computeWorldMatrix(true);
  11891. return this;
  11892. };
  11893. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11894. /**
  11895. * True if the World matrix has been frozen.
  11896. * Returns a boolean.
  11897. */
  11898. get: function () {
  11899. return this._isWorldMatrixFrozen;
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. /**
  11905. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11906. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11907. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11908. * The passed axis is also normalized.
  11909. * Returns the AbstractMesh.
  11910. */
  11911. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11912. axis.normalize();
  11913. if (!this.rotationQuaternion) {
  11914. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11915. this.rotation = BABYLON.Vector3.Zero();
  11916. }
  11917. var rotationQuaternion;
  11918. if (!space || space === BABYLON.Space.LOCAL) {
  11919. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11920. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11921. }
  11922. else {
  11923. if (this.parent) {
  11924. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11925. invertParentWorldMatrix.invert();
  11926. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11927. }
  11928. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11929. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11930. }
  11931. return this;
  11932. };
  11933. /**
  11934. * Translates the mesh along the axis vector for the passed distance in the given space.
  11935. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11936. * Returns the AbstractMesh.
  11937. */
  11938. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11939. var displacementVector = axis.scale(distance);
  11940. if (!space || space === BABYLON.Space.LOCAL) {
  11941. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11942. this.setPositionWithLocalVector(tempV3);
  11943. }
  11944. else {
  11945. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11946. }
  11947. return this;
  11948. };
  11949. /**
  11950. * Adds a rotation step to the mesh current rotation.
  11951. * x, y, z are Euler angles expressed in radians.
  11952. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11953. * This means this rotation is made in the mesh local space only.
  11954. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11955. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11956. * ```javascript
  11957. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11958. * ```
  11959. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11960. * 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.
  11961. * Returns the AbstractMesh.
  11962. */
  11963. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11964. var rotationQuaternion;
  11965. if (this.rotationQuaternion) {
  11966. rotationQuaternion = this.rotationQuaternion;
  11967. }
  11968. else {
  11969. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11970. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11971. }
  11972. var accumulation = BABYLON.Tmp.Quaternion[0];
  11973. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11974. rotationQuaternion.multiplyInPlace(accumulation);
  11975. if (!this.rotationQuaternion) {
  11976. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11977. }
  11978. return this;
  11979. };
  11980. /**
  11981. * Retuns the mesh absolute position in the World.
  11982. * Returns a Vector3.
  11983. */
  11984. AbstractMesh.prototype.getAbsolutePosition = function () {
  11985. this.computeWorldMatrix();
  11986. return this._absolutePosition;
  11987. };
  11988. /**
  11989. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11990. * Returns the AbstractMesh.
  11991. */
  11992. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11993. if (!absolutePosition) {
  11994. return;
  11995. }
  11996. var absolutePositionX;
  11997. var absolutePositionY;
  11998. var absolutePositionZ;
  11999. if (absolutePosition.x === undefined) {
  12000. if (arguments.length < 3) {
  12001. return;
  12002. }
  12003. absolutePositionX = arguments[0];
  12004. absolutePositionY = arguments[1];
  12005. absolutePositionZ = arguments[2];
  12006. }
  12007. else {
  12008. absolutePositionX = absolutePosition.x;
  12009. absolutePositionY = absolutePosition.y;
  12010. absolutePositionZ = absolutePosition.z;
  12011. }
  12012. if (this.parent) {
  12013. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12014. invertParentWorldMatrix.invert();
  12015. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12016. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12017. }
  12018. else {
  12019. this.position.x = absolutePositionX;
  12020. this.position.y = absolutePositionY;
  12021. this.position.z = absolutePositionZ;
  12022. }
  12023. return this;
  12024. };
  12025. // ================================== Point of View Movement =================================
  12026. /**
  12027. * Perform relative position change from the point of view of behind the front of the mesh.
  12028. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12029. * Supports definition of mesh facing forward or backward.
  12030. * @param {number} amountRight
  12031. * @param {number} amountUp
  12032. * @param {number} amountForward
  12033. *
  12034. * Returns the AbstractMesh.
  12035. */
  12036. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12037. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12038. return this;
  12039. };
  12040. /**
  12041. * Calculate relative position change from the point of view of behind the front of the mesh.
  12042. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12043. * Supports definition of mesh facing forward or backward.
  12044. * @param {number} amountRight
  12045. * @param {number} amountUp
  12046. * @param {number} amountForward
  12047. *
  12048. * Returns a new Vector3.
  12049. */
  12050. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12051. var rotMatrix = new BABYLON.Matrix();
  12052. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12053. rotQuaternion.toRotationMatrix(rotMatrix);
  12054. var translationDelta = BABYLON.Vector3.Zero();
  12055. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12056. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12057. return translationDelta;
  12058. };
  12059. // ================================== Point of View Rotation =================================
  12060. /**
  12061. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12062. * Supports definition of mesh facing forward or backward.
  12063. * @param {number} flipBack
  12064. * @param {number} twirlClockwise
  12065. * @param {number} tiltRight
  12066. *
  12067. * Returns the AbstractMesh.
  12068. */
  12069. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12070. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12071. return this;
  12072. };
  12073. /**
  12074. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12075. * Supports definition of mesh facing forward or backward.
  12076. * @param {number} flipBack
  12077. * @param {number} twirlClockwise
  12078. * @param {number} tiltRight
  12079. *
  12080. * Returns a new Vector3.
  12081. */
  12082. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12083. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12084. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12085. };
  12086. /**
  12087. * Sets a new pivot matrix to the mesh.
  12088. * Returns the AbstractMesh.
  12089. */
  12090. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12091. this._pivotMatrix = matrix;
  12092. this._cache.pivotMatrixUpdated = true;
  12093. return this;
  12094. };
  12095. /**
  12096. * Returns the mesh pivot matrix.
  12097. * Default : Identity.
  12098. * A Matrix is returned.
  12099. */
  12100. AbstractMesh.prototype.getPivotMatrix = function () {
  12101. return this._pivotMatrix;
  12102. };
  12103. AbstractMesh.prototype._isSynchronized = function () {
  12104. if (this._isDirty) {
  12105. return false;
  12106. }
  12107. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12108. return false;
  12109. if (this._cache.pivotMatrixUpdated) {
  12110. return false;
  12111. }
  12112. if (this.infiniteDistance) {
  12113. return false;
  12114. }
  12115. if (!this._cache.position.equals(this.position))
  12116. return false;
  12117. if (this.rotationQuaternion) {
  12118. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12119. return false;
  12120. }
  12121. if (!this._cache.rotation.equals(this.rotation))
  12122. return false;
  12123. if (!this._cache.scaling.equals(this.scaling))
  12124. return false;
  12125. return true;
  12126. };
  12127. AbstractMesh.prototype._initCache = function () {
  12128. _super.prototype._initCache.call(this);
  12129. this._cache.localMatrixUpdated = false;
  12130. this._cache.position = BABYLON.Vector3.Zero();
  12131. this._cache.scaling = BABYLON.Vector3.Zero();
  12132. this._cache.rotation = BABYLON.Vector3.Zero();
  12133. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12134. this._cache.billboardMode = -1;
  12135. };
  12136. AbstractMesh.prototype.markAsDirty = function (property) {
  12137. if (property === "rotation") {
  12138. this.rotationQuaternion = null;
  12139. }
  12140. this._currentRenderId = Number.MAX_VALUE;
  12141. this._isDirty = true;
  12142. return this;
  12143. };
  12144. /**
  12145. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12146. * Returns the AbstractMesh.
  12147. */
  12148. AbstractMesh.prototype._updateBoundingInfo = function () {
  12149. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12150. this._boundingInfo.update(this.worldMatrixFromCache);
  12151. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12152. return this;
  12153. };
  12154. /**
  12155. * Update a mesh's children BoundingInfo objects only.
  12156. * Returns the AbstractMesh.
  12157. */
  12158. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12159. if (!this.subMeshes) {
  12160. return;
  12161. }
  12162. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12163. var subMesh = this.subMeshes[subIndex];
  12164. if (!subMesh.IsGlobal) {
  12165. subMesh.updateBoundingInfo(matrix);
  12166. }
  12167. }
  12168. return this;
  12169. };
  12170. /**
  12171. * Computes the mesh World matrix and returns it.
  12172. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12173. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12174. * If the parameter `force`is set to `true`, the actual computation is done.
  12175. * Returns the mesh World Matrix.
  12176. */
  12177. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12178. if (this._isWorldMatrixFrozen) {
  12179. return this._worldMatrix;
  12180. }
  12181. if (!force && this.isSynchronized(true)) {
  12182. this._currentRenderId = this.getScene().getRenderId();
  12183. return this._worldMatrix;
  12184. }
  12185. this._cache.position.copyFrom(this.position);
  12186. this._cache.scaling.copyFrom(this.scaling);
  12187. this._cache.pivotMatrixUpdated = false;
  12188. this._cache.billboardMode = this.billboardMode;
  12189. this._currentRenderId = this.getScene().getRenderId();
  12190. this._isDirty = false;
  12191. // Scaling
  12192. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12193. // Rotation
  12194. //rotate, if quaternion is set and rotation was used
  12195. if (this.rotationQuaternion) {
  12196. var len = this.rotation.length();
  12197. if (len) {
  12198. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12199. this.rotation.copyFromFloats(0, 0, 0);
  12200. }
  12201. }
  12202. if (this.rotationQuaternion) {
  12203. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12204. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12205. }
  12206. else {
  12207. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12208. this._cache.rotation.copyFrom(this.rotation);
  12209. }
  12210. // Translation
  12211. if (this.infiniteDistance && !this.parent) {
  12212. var camera = this.getScene().activeCamera;
  12213. if (camera) {
  12214. var cameraWorldMatrix = camera.getWorldMatrix();
  12215. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12216. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12217. }
  12218. }
  12219. else {
  12220. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12221. }
  12222. // Composing transformations
  12223. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12224. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12225. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12226. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12227. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12228. // Need to decompose each rotation here
  12229. var currentPosition = BABYLON.Tmp.Vector3[3];
  12230. if (this.parent && this.parent.getWorldMatrix) {
  12231. if (this._meshToBoneReferal) {
  12232. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12233. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12234. }
  12235. else {
  12236. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12237. }
  12238. }
  12239. else {
  12240. currentPosition.copyFrom(this.position);
  12241. }
  12242. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12243. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12244. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12245. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12246. }
  12247. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12248. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12249. }
  12250. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12251. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12252. }
  12253. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12254. }
  12255. else {
  12256. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12257. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12258. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12259. }
  12260. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12261. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12262. }
  12263. // Local world
  12264. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12265. // Parent
  12266. if (this.parent && this.parent.getWorldMatrix) {
  12267. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12268. if (this._meshToBoneReferal) {
  12269. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12270. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12271. }
  12272. else {
  12273. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12274. }
  12275. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12276. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12277. this._worldMatrix.copyFrom(this._localWorld);
  12278. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12279. }
  12280. else {
  12281. if (this._meshToBoneReferal) {
  12282. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12283. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12284. }
  12285. else {
  12286. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12287. }
  12288. }
  12289. this._markSyncedWithParent();
  12290. }
  12291. else {
  12292. this._worldMatrix.copyFrom(this._localWorld);
  12293. }
  12294. // Bounding info
  12295. this._updateBoundingInfo();
  12296. // Absolute position
  12297. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12298. // Callbacks
  12299. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12300. if (!this._poseMatrix) {
  12301. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12302. }
  12303. return this._worldMatrix;
  12304. };
  12305. /**
  12306. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12307. * @param func: callback function to add
  12308. *
  12309. * Returns the AbstractMesh.
  12310. */
  12311. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12312. this.onAfterWorldMatrixUpdateObservable.add(func);
  12313. return this;
  12314. };
  12315. /**
  12316. * Removes a registered callback function.
  12317. * Returns the AbstractMesh.
  12318. */
  12319. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12320. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12321. return this;
  12322. };
  12323. /**
  12324. * Sets the mesh position in its local space.
  12325. * Returns the AbstractMesh.
  12326. */
  12327. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12328. this.computeWorldMatrix();
  12329. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12330. return this;
  12331. };
  12332. /**
  12333. * Returns the mesh position in the local space from the current World matrix values.
  12334. * Returns a new Vector3.
  12335. */
  12336. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12337. this.computeWorldMatrix();
  12338. var invLocalWorldMatrix = this._localWorld.clone();
  12339. invLocalWorldMatrix.invert();
  12340. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12341. };
  12342. /**
  12343. * Translates the mesh along the passed Vector3 in its local space.
  12344. * Returns the AbstractMesh.
  12345. */
  12346. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12347. this.computeWorldMatrix(true);
  12348. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12349. return this;
  12350. };
  12351. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12352. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12353. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12354. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12355. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12356. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12357. /// <returns>Mesh oriented towards targetMesh</returns>
  12358. if (yawCor === void 0) { yawCor = 0; }
  12359. if (pitchCor === void 0) { pitchCor = 0; }
  12360. if (rollCor === void 0) { rollCor = 0; }
  12361. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12362. var dv = AbstractMesh._lookAtVectorCache;
  12363. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12364. targetPoint.subtractToRef(pos, dv);
  12365. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12366. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12367. var pitch = Math.atan2(dv.y, len);
  12368. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12369. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12370. return this;
  12371. };
  12372. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12373. this._meshToBoneReferal = affectedMesh;
  12374. this.parent = bone;
  12375. if (bone.getWorldMatrix().determinant() < 0) {
  12376. this.scalingDeterminant *= -1;
  12377. }
  12378. return this;
  12379. };
  12380. AbstractMesh.prototype.detachFromBone = function () {
  12381. if (this.parent.getWorldMatrix().determinant() < 0) {
  12382. this.scalingDeterminant *= -1;
  12383. }
  12384. this._meshToBoneReferal = null;
  12385. this.parent = null;
  12386. return this;
  12387. };
  12388. /**
  12389. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12390. * A mesh is in the frustum if its bounding box intersects the frustum.
  12391. * Boolean returned.
  12392. */
  12393. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12394. return this._boundingInfo.isInFrustum(frustumPlanes);
  12395. };
  12396. /**
  12397. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12398. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12399. * Boolean returned.
  12400. */
  12401. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12402. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12403. ;
  12404. };
  12405. /**
  12406. * True if the mesh intersects another mesh or a SolidParticle object.
  12407. * 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)
  12408. * Returns a boolean.
  12409. */
  12410. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12411. if (!this._boundingInfo || !mesh._boundingInfo) {
  12412. return false;
  12413. }
  12414. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12415. };
  12416. /**
  12417. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12418. * Returns a boolean.
  12419. */
  12420. AbstractMesh.prototype.intersectsPoint = function (point) {
  12421. if (!this._boundingInfo) {
  12422. return false;
  12423. }
  12424. return this._boundingInfo.intersectsPoint(point);
  12425. };
  12426. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12427. return this.physicsImpostor;
  12428. };
  12429. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12430. if (!camera) {
  12431. camera = this.getScene().activeCamera;
  12432. }
  12433. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12434. };
  12435. /**
  12436. * Returns the distance from the mesh to the active camera.
  12437. * Returns a float.
  12438. */
  12439. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12440. if (!camera) {
  12441. camera = this.getScene().activeCamera;
  12442. }
  12443. return this.absolutePosition.subtract(camera.position).length();
  12444. };
  12445. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12446. if (!this.physicsImpostor) {
  12447. return;
  12448. }
  12449. this.physicsImpostor.applyImpulse(force, contactPoint);
  12450. return this;
  12451. };
  12452. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12453. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12454. return;
  12455. }
  12456. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12457. mainPivot: pivot1,
  12458. connectedPivot: pivot2,
  12459. nativeParams: options
  12460. });
  12461. return this;
  12462. };
  12463. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12464. // Collisions
  12465. /**
  12466. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12467. * Default `false`.
  12468. */
  12469. get: function () {
  12470. return this._checkCollisions;
  12471. },
  12472. set: function (collisionEnabled) {
  12473. this._checkCollisions = collisionEnabled;
  12474. if (this.getScene().workerCollisions) {
  12475. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12476. }
  12477. },
  12478. enumerable: true,
  12479. configurable: true
  12480. });
  12481. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12482. var globalPosition = this.getAbsolutePosition();
  12483. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12484. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12485. if (!this._collider) {
  12486. this._collider = new BABYLON.Collider();
  12487. }
  12488. this._collider.radius = this.ellipsoid;
  12489. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12490. return this;
  12491. };
  12492. // Submeshes octree
  12493. /**
  12494. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12495. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12496. * Returns an Octree of submeshes.
  12497. */
  12498. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12499. if (maxCapacity === void 0) { maxCapacity = 64; }
  12500. if (maxDepth === void 0) { maxDepth = 2; }
  12501. if (!this._submeshesOctree) {
  12502. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12503. }
  12504. this.computeWorldMatrix(true);
  12505. // Update octree
  12506. var bbox = this.getBoundingInfo().boundingBox;
  12507. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12508. return this._submeshesOctree;
  12509. };
  12510. // Collisions
  12511. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12512. this._generatePointsArray();
  12513. // Transformation
  12514. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12515. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12516. subMesh._lastColliderWorldVertices = [];
  12517. subMesh._trianglePlanes = [];
  12518. var start = subMesh.verticesStart;
  12519. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12520. for (var i = start; i < end; i++) {
  12521. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12522. }
  12523. }
  12524. // Collide
  12525. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12526. if (collider.collisionFound) {
  12527. collider.collidedMesh = this;
  12528. }
  12529. return this;
  12530. };
  12531. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12532. var subMeshes;
  12533. var len;
  12534. // Octrees
  12535. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12536. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12537. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12538. len = intersections.length;
  12539. subMeshes = intersections.data;
  12540. }
  12541. else {
  12542. subMeshes = this.subMeshes;
  12543. len = subMeshes.length;
  12544. }
  12545. for (var index = 0; index < len; index++) {
  12546. var subMesh = subMeshes[index];
  12547. // Bounding test
  12548. if (len > 1 && !subMesh._checkCollision(collider))
  12549. continue;
  12550. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12551. }
  12552. return this;
  12553. };
  12554. AbstractMesh.prototype._checkCollision = function (collider) {
  12555. // Bounding box test
  12556. if (!this._boundingInfo._checkCollision(collider))
  12557. return this;
  12558. // Transformation matrix
  12559. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12560. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12561. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12562. return this;
  12563. };
  12564. // Picking
  12565. AbstractMesh.prototype._generatePointsArray = function () {
  12566. return false;
  12567. };
  12568. /**
  12569. * Checks if the passed Ray intersects with the mesh.
  12570. * Returns an object PickingInfo.
  12571. */
  12572. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12573. var pickingInfo = new BABYLON.PickingInfo();
  12574. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12575. return pickingInfo;
  12576. }
  12577. if (!this._generatePointsArray()) {
  12578. return pickingInfo;
  12579. }
  12580. var intersectInfo = null;
  12581. // Octrees
  12582. var subMeshes;
  12583. var len;
  12584. if (this._submeshesOctree && this.useOctreeForPicking) {
  12585. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12586. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12587. len = intersections.length;
  12588. subMeshes = intersections.data;
  12589. }
  12590. else {
  12591. subMeshes = this.subMeshes;
  12592. len = subMeshes.length;
  12593. }
  12594. for (var index = 0; index < len; index++) {
  12595. var subMesh = subMeshes[index];
  12596. // Bounding test
  12597. if (len > 1 && !subMesh.canIntersects(ray))
  12598. continue;
  12599. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12600. if (currentIntersectInfo) {
  12601. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12602. intersectInfo = currentIntersectInfo;
  12603. intersectInfo.subMeshId = index;
  12604. if (fastCheck) {
  12605. break;
  12606. }
  12607. }
  12608. }
  12609. }
  12610. if (intersectInfo) {
  12611. // Get picked point
  12612. var world = this.getWorldMatrix();
  12613. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12614. var direction = ray.direction.clone();
  12615. direction = direction.scale(intersectInfo.distance);
  12616. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12617. var pickedPoint = worldOrigin.add(worldDirection);
  12618. // Return result
  12619. pickingInfo.hit = true;
  12620. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12621. pickingInfo.pickedPoint = pickedPoint;
  12622. pickingInfo.pickedMesh = this;
  12623. pickingInfo.bu = intersectInfo.bu;
  12624. pickingInfo.bv = intersectInfo.bv;
  12625. pickingInfo.faceId = intersectInfo.faceId;
  12626. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12627. return pickingInfo;
  12628. }
  12629. return pickingInfo;
  12630. };
  12631. /**
  12632. * Clones the mesh, used by the class Mesh.
  12633. * Just returns `null` for an AbstractMesh.
  12634. */
  12635. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12636. return null;
  12637. };
  12638. /**
  12639. * Disposes all the mesh submeshes.
  12640. * Returns the AbstractMesh.
  12641. */
  12642. AbstractMesh.prototype.releaseSubMeshes = function () {
  12643. if (this.subMeshes) {
  12644. while (this.subMeshes.length) {
  12645. this.subMeshes[0].dispose();
  12646. }
  12647. }
  12648. else {
  12649. this.subMeshes = new Array();
  12650. }
  12651. return this;
  12652. };
  12653. /**
  12654. * Disposes the AbstractMesh.
  12655. * Some internal references are kept for further use.
  12656. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12657. * Returns nothing.
  12658. */
  12659. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12660. var _this = this;
  12661. var index;
  12662. // Action manager
  12663. if (this.actionManager) {
  12664. this.actionManager.dispose();
  12665. this.actionManager = null;
  12666. }
  12667. // Skeleton
  12668. this.skeleton = null;
  12669. // Animations
  12670. this.getScene().stopAnimation(this);
  12671. // Physics
  12672. if (this.physicsImpostor) {
  12673. this.physicsImpostor.dispose();
  12674. }
  12675. // Intersections in progress
  12676. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12677. var other = this._intersectionsInProgress[index];
  12678. var pos = other._intersectionsInProgress.indexOf(this);
  12679. other._intersectionsInProgress.splice(pos, 1);
  12680. }
  12681. this._intersectionsInProgress = [];
  12682. // Lights
  12683. var lights = this.getScene().lights;
  12684. lights.forEach(function (light) {
  12685. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12686. if (meshIndex !== -1) {
  12687. light.includedOnlyMeshes.splice(meshIndex, 1);
  12688. }
  12689. meshIndex = light.excludedMeshes.indexOf(_this);
  12690. if (meshIndex !== -1) {
  12691. light.excludedMeshes.splice(meshIndex, 1);
  12692. }
  12693. // Shadow generators
  12694. var generator = light.getShadowGenerator();
  12695. if (generator) {
  12696. var shadowMap = generator.getShadowMap();
  12697. meshIndex = shadowMap.renderList.indexOf(_this);
  12698. if (meshIndex !== -1) {
  12699. shadowMap.renderList.splice(meshIndex, 1);
  12700. }
  12701. }
  12702. });
  12703. // Edges
  12704. if (this._edgesRenderer) {
  12705. this._edgesRenderer.dispose();
  12706. this._edgesRenderer = null;
  12707. }
  12708. // SubMeshes
  12709. if (this.getClassName() !== "InstancedMesh") {
  12710. this.releaseSubMeshes();
  12711. }
  12712. // Octree
  12713. var sceneOctree = this.getScene().selectionOctree;
  12714. if (sceneOctree) {
  12715. var index = sceneOctree.dynamicContent.indexOf(this);
  12716. if (index !== -1) {
  12717. sceneOctree.dynamicContent.splice(index, 1);
  12718. }
  12719. }
  12720. // Engine
  12721. this.getScene().getEngine().wipeCaches();
  12722. // Remove from scene
  12723. this.getScene().removeMesh(this);
  12724. if (!doNotRecurse) {
  12725. // Particles
  12726. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12727. if (this.getScene().particleSystems[index].emitter === this) {
  12728. this.getScene().particleSystems[index].dispose();
  12729. index--;
  12730. }
  12731. }
  12732. // Children
  12733. var objects = this.getDescendants(true);
  12734. for (index = 0; index < objects.length; index++) {
  12735. objects[index].dispose();
  12736. }
  12737. }
  12738. else {
  12739. var childMeshes = this.getChildMeshes(true);
  12740. for (index = 0; index < childMeshes.length; index++) {
  12741. var child = childMeshes[index];
  12742. child.parent = null;
  12743. child.computeWorldMatrix(true);
  12744. }
  12745. }
  12746. // facet data
  12747. if (this._facetDataEnabled) {
  12748. this.disableFacetData();
  12749. }
  12750. this.onAfterWorldMatrixUpdateObservable.clear();
  12751. this.onCollideObservable.clear();
  12752. this.onCollisionPositionChangeObservable.clear();
  12753. this._isDisposed = true;
  12754. _super.prototype.dispose.call(this);
  12755. };
  12756. /**
  12757. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12758. * This Vector3 is expressed in the World space.
  12759. */
  12760. AbstractMesh.prototype.getDirection = function (localAxis) {
  12761. var result = BABYLON.Vector3.Zero();
  12762. this.getDirectionToRef(localAxis, result);
  12763. return result;
  12764. };
  12765. /**
  12766. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12767. * localAxis is expressed in the mesh local space.
  12768. * result is computed in the Wordl space from the mesh World matrix.
  12769. * Returns the AbstractMesh.
  12770. */
  12771. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12772. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12773. return this;
  12774. };
  12775. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12776. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12777. if (this.getScene().getRenderId() == 0) {
  12778. this.computeWorldMatrix(true);
  12779. }
  12780. var wm = this.getWorldMatrix();
  12781. if (space == BABYLON.Space.WORLD) {
  12782. var tmat = BABYLON.Tmp.Matrix[0];
  12783. wm.invertToRef(tmat);
  12784. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12785. }
  12786. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12787. this._pivotMatrix.m[12] = -point.x;
  12788. this._pivotMatrix.m[13] = -point.y;
  12789. this._pivotMatrix.m[14] = -point.z;
  12790. this._cache.pivotMatrixUpdated = true;
  12791. return this;
  12792. };
  12793. /**
  12794. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12795. */
  12796. AbstractMesh.prototype.getPivotPoint = function () {
  12797. var point = BABYLON.Vector3.Zero();
  12798. this.getPivotPointToRef(point);
  12799. return point;
  12800. };
  12801. /**
  12802. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12803. * Returns the AbstractMesh.
  12804. */
  12805. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12806. result.x = -this._pivotMatrix.m[12];
  12807. result.y = -this._pivotMatrix.m[13];
  12808. result.z = -this._pivotMatrix.m[14];
  12809. return this;
  12810. };
  12811. /**
  12812. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12813. */
  12814. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12815. var point = BABYLON.Vector3.Zero();
  12816. this.getAbsolutePivotPointToRef(point);
  12817. return point;
  12818. };
  12819. /**
  12820. * Defines the passed mesh as the parent of the current mesh.
  12821. * Returns the AbstractMesh.
  12822. */
  12823. AbstractMesh.prototype.setParent = function (mesh) {
  12824. var child = this;
  12825. var parent = mesh;
  12826. if (mesh == null) {
  12827. var rotation = BABYLON.Tmp.Quaternion[0];
  12828. var position = BABYLON.Tmp.Vector3[0];
  12829. var scale = BABYLON.Tmp.Vector3[1];
  12830. child.getWorldMatrix().decompose(scale, rotation, position);
  12831. if (child.rotationQuaternion) {
  12832. child.rotationQuaternion.copyFrom(rotation);
  12833. }
  12834. else {
  12835. rotation.toEulerAnglesToRef(child.rotation);
  12836. }
  12837. child.position.x = position.x;
  12838. child.position.y = position.y;
  12839. child.position.z = position.z;
  12840. }
  12841. else {
  12842. var rotation = BABYLON.Tmp.Quaternion[0];
  12843. var position = BABYLON.Tmp.Vector3[0];
  12844. var scale = BABYLON.Tmp.Vector3[1];
  12845. var m1 = BABYLON.Tmp.Matrix[0];
  12846. var m2 = BABYLON.Tmp.Matrix[1];
  12847. parent.getWorldMatrix().decompose(scale, rotation, position);
  12848. rotation.toRotationMatrix(m1);
  12849. m2.setTranslation(position);
  12850. m2.multiplyToRef(m1, m1);
  12851. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12852. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12853. m.decompose(scale, rotation, position);
  12854. if (child.rotationQuaternion) {
  12855. child.rotationQuaternion.copyFrom(rotation);
  12856. }
  12857. else {
  12858. rotation.toEulerAnglesToRef(child.rotation);
  12859. }
  12860. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12861. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12862. m.decompose(scale, rotation, position);
  12863. child.position.x = position.x;
  12864. child.position.y = position.y;
  12865. child.position.z = position.z;
  12866. }
  12867. child.parent = parent;
  12868. return this;
  12869. };
  12870. /**
  12871. * Adds the passed mesh as a child to the current mesh.
  12872. * Returns the AbstractMesh.
  12873. */
  12874. AbstractMesh.prototype.addChild = function (mesh) {
  12875. mesh.setParent(this);
  12876. return this;
  12877. };
  12878. /**
  12879. * Removes the passed mesh from the current mesh children list.
  12880. * Returns the AbstractMesh.
  12881. */
  12882. AbstractMesh.prototype.removeChild = function (mesh) {
  12883. mesh.setParent(null);
  12884. return this;
  12885. };
  12886. /**
  12887. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12888. * Returns the AbstractMesh.
  12889. */
  12890. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12891. result.x = this._pivotMatrix.m[12];
  12892. result.y = this._pivotMatrix.m[13];
  12893. result.z = this._pivotMatrix.m[14];
  12894. this.getPivotPointToRef(result);
  12895. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12896. return this;
  12897. };
  12898. // Facet data
  12899. /**
  12900. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12901. * Returns the AbstractMesh.
  12902. */
  12903. AbstractMesh.prototype._initFacetData = function () {
  12904. if (!this._facetNormals) {
  12905. this._facetNormals = new Array();
  12906. }
  12907. if (!this._facetPositions) {
  12908. this._facetPositions = new Array();
  12909. }
  12910. if (!this._facetPartitioning) {
  12911. this._facetPartitioning = new Array();
  12912. }
  12913. this._facetNb = this.getIndices().length / 3;
  12914. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12915. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12916. for (var f = 0; f < this._facetNb; f++) {
  12917. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12918. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12919. }
  12920. this._facetDataEnabled = true;
  12921. return this;
  12922. };
  12923. /**
  12924. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12925. * This method can be called within the render loop.
  12926. * 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.
  12927. * Returns the AbstractMesh.
  12928. */
  12929. AbstractMesh.prototype.updateFacetData = function () {
  12930. if (!this._facetDataEnabled) {
  12931. this._initFacetData();
  12932. }
  12933. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12934. var indices = this.getIndices();
  12935. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12936. var bInfo = this.getBoundingInfo();
  12937. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12938. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12939. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12940. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12941. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12942. this._subDiv.max = this._partitioningSubdivisions;
  12943. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12944. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12945. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12946. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12947. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12948. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12949. // set the parameters for ComputeNormals()
  12950. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12951. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12952. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12953. this._facetParameters.bInfo = bInfo;
  12954. this._facetParameters.bbSize = this._bbSize;
  12955. this._facetParameters.subDiv = this._subDiv;
  12956. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12957. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12958. return this;
  12959. };
  12960. /**
  12961. * Returns the facetLocalNormals array.
  12962. * The normals are expressed in the mesh local space.
  12963. */
  12964. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12965. if (!this._facetNormals) {
  12966. this.updateFacetData();
  12967. }
  12968. return this._facetNormals;
  12969. };
  12970. /**
  12971. * Returns the facetLocalPositions array.
  12972. * The facet positions are expressed in the mesh local space.
  12973. */
  12974. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12975. if (!this._facetPositions) {
  12976. this.updateFacetData();
  12977. }
  12978. return this._facetPositions;
  12979. };
  12980. /**
  12981. * Returns the facetLocalPartioning array.
  12982. */
  12983. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12984. if (!this._facetPartitioning) {
  12985. this.updateFacetData();
  12986. }
  12987. return this._facetPartitioning;
  12988. };
  12989. /**
  12990. * Returns the i-th facet position in the world system.
  12991. * This method allocates a new Vector3 per call.
  12992. */
  12993. AbstractMesh.prototype.getFacetPosition = function (i) {
  12994. var pos = BABYLON.Vector3.Zero();
  12995. this.getFacetPositionToRef(i, pos);
  12996. return pos;
  12997. };
  12998. /**
  12999. * Sets the reference Vector3 with the i-th facet position in the world system.
  13000. * Returns the AbstractMesh.
  13001. */
  13002. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13003. var localPos = (this.getFacetLocalPositions())[i];
  13004. var world = this.getWorldMatrix();
  13005. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13006. return this;
  13007. };
  13008. /**
  13009. * Returns the i-th facet normal in the world system.
  13010. * This method allocates a new Vector3 per call.
  13011. */
  13012. AbstractMesh.prototype.getFacetNormal = function (i) {
  13013. var norm = BABYLON.Vector3.Zero();
  13014. this.getFacetNormalToRef(i, norm);
  13015. return norm;
  13016. };
  13017. /**
  13018. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13019. * Returns the AbstractMesh.
  13020. */
  13021. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13022. var localNorm = (this.getFacetLocalNormals())[i];
  13023. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13024. return this;
  13025. };
  13026. /**
  13027. * 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).
  13028. */
  13029. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13030. var bInfo = this.getBoundingInfo();
  13031. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13032. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13033. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13034. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13035. return null;
  13036. }
  13037. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13038. };
  13039. /**
  13040. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13041. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13042. * 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.
  13043. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13044. * 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.
  13045. */
  13046. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13047. if (checkFace === void 0) { checkFace = false; }
  13048. if (facing === void 0) { facing = true; }
  13049. var world = this.getWorldMatrix();
  13050. var invMat = BABYLON.Tmp.Matrix[5];
  13051. world.invertToRef(invMat);
  13052. var invVect = BABYLON.Tmp.Vector3[8];
  13053. var closest = null;
  13054. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13055. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13056. if (projected) {
  13057. // tranform the local computed projected vector to world coordinates
  13058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13059. }
  13060. return closest;
  13061. };
  13062. /**
  13063. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13064. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13065. * 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.
  13066. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13067. * 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.
  13068. */
  13069. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13070. if (checkFace === void 0) { checkFace = false; }
  13071. if (facing === void 0) { facing = true; }
  13072. var closest = null;
  13073. var tmpx = 0.0;
  13074. var tmpy = 0.0;
  13075. var tmpz = 0.0;
  13076. var d = 0.0; // tmp dot facet normal * facet position
  13077. var t0 = 0.0;
  13078. var projx = 0.0;
  13079. var projy = 0.0;
  13080. var projz = 0.0;
  13081. // Get all the facets in the same partitioning block than (x, y, z)
  13082. var facetPositions = this.getFacetLocalPositions();
  13083. var facetNormals = this.getFacetLocalNormals();
  13084. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13085. if (!facetsInBlock) {
  13086. return null;
  13087. }
  13088. // Get the closest facet to (x, y, z)
  13089. var shortest = Number.MAX_VALUE; // init distance vars
  13090. var tmpDistance = shortest;
  13091. var fib; // current facet in the block
  13092. var norm; // current facet normal
  13093. var p0; // current facet barycenter position
  13094. // loop on all the facets in the current partitioning block
  13095. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13096. fib = facetsInBlock[idx];
  13097. norm = facetNormals[fib];
  13098. p0 = facetPositions[fib];
  13099. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13100. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13101. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13102. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13103. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13104. projx = x + norm.x * t0;
  13105. projy = y + norm.y * t0;
  13106. projz = z + norm.z * t0;
  13107. tmpx = projx - x;
  13108. tmpy = projy - y;
  13109. tmpz = projz - z;
  13110. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13111. if (tmpDistance < shortest) {
  13112. shortest = tmpDistance;
  13113. closest = fib;
  13114. if (projected) {
  13115. projected.x = projx;
  13116. projected.y = projy;
  13117. projected.z = projz;
  13118. }
  13119. }
  13120. }
  13121. }
  13122. return closest;
  13123. };
  13124. /**
  13125. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13126. */
  13127. AbstractMesh.prototype.getFacetDataParameters = function () {
  13128. return this._facetParameters;
  13129. };
  13130. /**
  13131. * Disables the feature FacetData and frees the related memory.
  13132. * Returns the AbstractMesh.
  13133. */
  13134. AbstractMesh.prototype.disableFacetData = function () {
  13135. if (this._facetDataEnabled) {
  13136. this._facetDataEnabled = false;
  13137. this._facetPositions = null;
  13138. this._facetNormals = null;
  13139. this._facetPartitioning = null;
  13140. this._facetParameters = null;
  13141. }
  13142. return this;
  13143. };
  13144. /**
  13145. * Creates new normals data for the mesh.
  13146. * @param updatable.
  13147. */
  13148. AbstractMesh.prototype.createNormals = function (updatable) {
  13149. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13150. var indices = this.getIndices();
  13151. var normals;
  13152. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13153. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13154. }
  13155. else {
  13156. normals = [];
  13157. }
  13158. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13159. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13160. };
  13161. return AbstractMesh;
  13162. }(BABYLON.Node));
  13163. // Statics
  13164. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13165. AbstractMesh._BILLBOARDMODE_X = 1;
  13166. AbstractMesh._BILLBOARDMODE_Y = 2;
  13167. AbstractMesh._BILLBOARDMODE_Z = 4;
  13168. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13169. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13170. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13171. BABYLON.AbstractMesh = AbstractMesh;
  13172. })(BABYLON || (BABYLON = {}));
  13173. //# sourceMappingURL=babylon.abstractMesh.js.map
  13174. var BABYLON;
  13175. (function (BABYLON) {
  13176. var Light = (function (_super) {
  13177. __extends(Light, _super);
  13178. /**
  13179. * Creates a Light object in the scene.
  13180. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13181. */
  13182. function Light(name, scene) {
  13183. var _this = _super.call(this, name, scene) || this;
  13184. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13185. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13186. _this.intensity = 1.0;
  13187. _this.range = Number.MAX_VALUE;
  13188. /**
  13189. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13190. * of light.
  13191. */
  13192. _this._photometricScale = 1.0;
  13193. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13194. _this._radius = 0.00001;
  13195. _this.renderPriority = 0;
  13196. /**
  13197. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13198. * the current shadow generator.
  13199. */
  13200. _this.shadowEnabled = true;
  13201. _this._excludeWithLayerMask = 0;
  13202. _this._includeOnlyWithLayerMask = 0;
  13203. _this._lightmapMode = 0;
  13204. _this._excludedMeshesIds = new Array();
  13205. _this._includedOnlyMeshesIds = new Array();
  13206. _this.getScene().addLight(_this);
  13207. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13208. _this._buildUniformLayout();
  13209. _this.includedOnlyMeshes = new Array();
  13210. _this.excludedMeshes = new Array();
  13211. _this._resyncMeshes();
  13212. return _this;
  13213. }
  13214. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13215. /**
  13216. * If every light affecting the material is in this lightmapMode,
  13217. * material.lightmapTexture adds or multiplies
  13218. * (depends on material.useLightmapAsShadowmap)
  13219. * after every other light calculations.
  13220. */
  13221. get: function () {
  13222. return Light._LIGHTMAP_DEFAULT;
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13228. /**
  13229. * material.lightmapTexture as only diffuse lighting from this light
  13230. * adds pnly specular lighting from this light
  13231. * adds dynamic shadows
  13232. */
  13233. get: function () {
  13234. return Light._LIGHTMAP_SPECULAR;
  13235. },
  13236. enumerable: true,
  13237. configurable: true
  13238. });
  13239. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13240. /**
  13241. * material.lightmapTexture as only lighting
  13242. * no light calculation from this light
  13243. * only adds dynamic shadows from this light
  13244. */
  13245. get: function () {
  13246. return Light._LIGHTMAP_SHADOWSONLY;
  13247. },
  13248. enumerable: true,
  13249. configurable: true
  13250. });
  13251. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13252. /**
  13253. * Each light type uses the default quantity according to its type:
  13254. * point/spot lights use luminous intensity
  13255. * directional lights use illuminance
  13256. */
  13257. get: function () {
  13258. return Light._INTENSITYMODE_AUTOMATIC;
  13259. },
  13260. enumerable: true,
  13261. configurable: true
  13262. });
  13263. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13264. /**
  13265. * lumen (lm)
  13266. */
  13267. get: function () {
  13268. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13269. },
  13270. enumerable: true,
  13271. configurable: true
  13272. });
  13273. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13274. /**
  13275. * candela (lm/sr)
  13276. */
  13277. get: function () {
  13278. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13279. },
  13280. enumerable: true,
  13281. configurable: true
  13282. });
  13283. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13284. /**
  13285. * lux (lm/m^2)
  13286. */
  13287. get: function () {
  13288. return Light._INTENSITYMODE_ILLUMINANCE;
  13289. },
  13290. enumerable: true,
  13291. configurable: true
  13292. });
  13293. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13294. /**
  13295. * nit (cd/m^2)
  13296. */
  13297. get: function () {
  13298. return Light._INTENSITYMODE_LUMINANCE;
  13299. },
  13300. enumerable: true,
  13301. configurable: true
  13302. });
  13303. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13304. /**
  13305. * Light type const id of the point light.
  13306. */
  13307. get: function () {
  13308. return Light._LIGHTTYPEID_POINTLIGHT;
  13309. },
  13310. enumerable: true,
  13311. configurable: true
  13312. });
  13313. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13314. /**
  13315. * Light type const id of the directional light.
  13316. */
  13317. get: function () {
  13318. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13319. },
  13320. enumerable: true,
  13321. configurable: true
  13322. });
  13323. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13324. /**
  13325. * Light type const id of the spot light.
  13326. */
  13327. get: function () {
  13328. return Light._LIGHTTYPEID_SPOTLIGHT;
  13329. },
  13330. enumerable: true,
  13331. configurable: true
  13332. });
  13333. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13334. /**
  13335. * Light type const id of the hemispheric light.
  13336. */
  13337. get: function () {
  13338. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13339. },
  13340. enumerable: true,
  13341. configurable: true
  13342. });
  13343. Object.defineProperty(Light.prototype, "intensityMode", {
  13344. /**
  13345. * Gets the photometric scale used to interpret the intensity.
  13346. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13347. */
  13348. get: function () {
  13349. return this._intensityMode;
  13350. },
  13351. /**
  13352. * Sets the photometric scale used to interpret the intensity.
  13353. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13354. */
  13355. set: function (value) {
  13356. this._intensityMode = value;
  13357. this._computePhotometricScale();
  13358. },
  13359. enumerable: true,
  13360. configurable: true
  13361. });
  13362. ;
  13363. ;
  13364. Object.defineProperty(Light.prototype, "radius", {
  13365. /**
  13366. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13367. */
  13368. get: function () {
  13369. return this._radius;
  13370. },
  13371. /**
  13372. * sets the light radius used by PBR Materials to simulate soft area lights.
  13373. */
  13374. set: function (value) {
  13375. this._radius = value;
  13376. this._computePhotometricScale();
  13377. },
  13378. enumerable: true,
  13379. configurable: true
  13380. });
  13381. ;
  13382. ;
  13383. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13384. get: function () {
  13385. return this._includedOnlyMeshes;
  13386. },
  13387. set: function (value) {
  13388. this._includedOnlyMeshes = value;
  13389. this._hookArrayForIncludedOnly(value);
  13390. },
  13391. enumerable: true,
  13392. configurable: true
  13393. });
  13394. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13395. get: function () {
  13396. return this._excludedMeshes;
  13397. },
  13398. set: function (value) {
  13399. this._excludedMeshes = value;
  13400. this._hookArrayForExcluded(value);
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13406. get: function () {
  13407. return this._excludeWithLayerMask;
  13408. },
  13409. set: function (value) {
  13410. this._excludeWithLayerMask = value;
  13411. this._resyncMeshes();
  13412. },
  13413. enumerable: true,
  13414. configurable: true
  13415. });
  13416. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13417. get: function () {
  13418. return this._includeOnlyWithLayerMask;
  13419. },
  13420. set: function (value) {
  13421. this._includeOnlyWithLayerMask = value;
  13422. this._resyncMeshes();
  13423. },
  13424. enumerable: true,
  13425. configurable: true
  13426. });
  13427. Object.defineProperty(Light.prototype, "lightmapMode", {
  13428. get: function () {
  13429. return this._lightmapMode;
  13430. },
  13431. set: function (value) {
  13432. if (this._lightmapMode === value) {
  13433. return;
  13434. }
  13435. this._lightmapMode = value;
  13436. this._markMeshesAsLightDirty();
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. Light.prototype._buildUniformLayout = function () {
  13442. // Overridden
  13443. };
  13444. /**
  13445. * Returns the string "Light".
  13446. */
  13447. Light.prototype.getClassName = function () {
  13448. return "Light";
  13449. };
  13450. /**
  13451. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13452. */
  13453. Light.prototype.toString = function (fullDetails) {
  13454. var ret = "Name: " + this.name;
  13455. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13456. if (this.animations) {
  13457. for (var i = 0; i < this.animations.length; i++) {
  13458. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13459. }
  13460. }
  13461. if (fullDetails) {
  13462. }
  13463. return ret;
  13464. };
  13465. /**
  13466. * Set the enabled state of this node.
  13467. * @param {boolean} value - the new enabled state
  13468. * @see isEnabled
  13469. */
  13470. Light.prototype.setEnabled = function (value) {
  13471. _super.prototype.setEnabled.call(this, value);
  13472. this._resyncMeshes();
  13473. };
  13474. /**
  13475. * Returns the Light associated shadow generator.
  13476. */
  13477. Light.prototype.getShadowGenerator = function () {
  13478. return this._shadowGenerator;
  13479. };
  13480. /**
  13481. * Returns a Vector3, the absolute light position in the World.
  13482. */
  13483. Light.prototype.getAbsolutePosition = function () {
  13484. return BABYLON.Vector3.Zero();
  13485. };
  13486. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13487. };
  13488. Light.prototype._getWorldMatrix = function () {
  13489. return BABYLON.Matrix.Identity();
  13490. };
  13491. /**
  13492. * Boolean : True if the light will affect the passed mesh.
  13493. */
  13494. Light.prototype.canAffectMesh = function (mesh) {
  13495. if (!mesh) {
  13496. return true;
  13497. }
  13498. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13499. return false;
  13500. }
  13501. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13502. return false;
  13503. }
  13504. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13505. return false;
  13506. }
  13507. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13508. return false;
  13509. }
  13510. return true;
  13511. };
  13512. /**
  13513. * Returns the light World matrix.
  13514. */
  13515. Light.prototype.getWorldMatrix = function () {
  13516. this._currentRenderId = this.getScene().getRenderId();
  13517. var worldMatrix = this._getWorldMatrix();
  13518. if (this.parent && this.parent.getWorldMatrix) {
  13519. if (!this._parentedWorldMatrix) {
  13520. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13521. }
  13522. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13523. this._markSyncedWithParent();
  13524. return this._parentedWorldMatrix;
  13525. }
  13526. return worldMatrix;
  13527. };
  13528. /**
  13529. * Sort function to order lights for rendering.
  13530. * @param a First Light object to compare to second.
  13531. * @param b Second Light object to compare first.
  13532. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13533. */
  13534. Light.compareLightsPriority = function (a, b) {
  13535. //shadow-casting lights have priority over non-shadow-casting lights
  13536. //the renderPrioirty is a secondary sort criterion
  13537. if (a.shadowEnabled !== b.shadowEnabled) {
  13538. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13539. }
  13540. return b.renderPriority - a.renderPriority;
  13541. };
  13542. /**
  13543. * Disposes the light.
  13544. */
  13545. Light.prototype.dispose = function () {
  13546. if (this._shadowGenerator) {
  13547. this._shadowGenerator.dispose();
  13548. this._shadowGenerator = null;
  13549. }
  13550. // Animations
  13551. this.getScene().stopAnimation(this);
  13552. // Remove from meshes
  13553. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13554. var mesh = _a[_i];
  13555. mesh._removeLightSource(this);
  13556. }
  13557. this._uniformBuffer.dispose();
  13558. // Remove from scene
  13559. this.getScene().removeLight(this);
  13560. _super.prototype.dispose.call(this);
  13561. };
  13562. /**
  13563. * Returns the light type ID (integer).
  13564. */
  13565. Light.prototype.getTypeID = function () {
  13566. return 0;
  13567. };
  13568. /**
  13569. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13570. */
  13571. Light.prototype.getScaledIntensity = function () {
  13572. return this._photometricScale * this.intensity;
  13573. };
  13574. /**
  13575. * Returns a new Light object, named "name", from the current one.
  13576. */
  13577. Light.prototype.clone = function (name) {
  13578. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13579. };
  13580. /**
  13581. * Serializes the current light into a Serialization object.
  13582. * Returns the serialized object.
  13583. */
  13584. Light.prototype.serialize = function () {
  13585. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13586. // Type
  13587. serializationObject.type = this.getTypeID();
  13588. // Parent
  13589. if (this.parent) {
  13590. serializationObject.parentId = this.parent.id;
  13591. }
  13592. // Inclusion / exclusions
  13593. if (this.excludedMeshes.length > 0) {
  13594. serializationObject.excludedMeshesIds = [];
  13595. this.excludedMeshes.forEach(function (mesh) {
  13596. serializationObject.excludedMeshesIds.push(mesh.id);
  13597. });
  13598. }
  13599. if (this.includedOnlyMeshes.length > 0) {
  13600. serializationObject.includedOnlyMeshesIds = [];
  13601. this.includedOnlyMeshes.forEach(function (mesh) {
  13602. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13603. });
  13604. }
  13605. // Animations
  13606. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13607. serializationObject.ranges = this.serializeAnimationRanges();
  13608. return serializationObject;
  13609. };
  13610. /**
  13611. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13612. * This new light is named "name" and added to the passed scene.
  13613. */
  13614. Light.GetConstructorFromName = function (type, name, scene) {
  13615. switch (type) {
  13616. case 0:
  13617. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13618. case 1:
  13619. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13620. case 2:
  13621. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13622. case 3:
  13623. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13624. }
  13625. };
  13626. /**
  13627. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13628. */
  13629. Light.Parse = function (parsedLight, scene) {
  13630. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13631. // Inclusion / exclusions
  13632. if (parsedLight.excludedMeshesIds) {
  13633. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13634. }
  13635. if (parsedLight.includedOnlyMeshesIds) {
  13636. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13637. }
  13638. // Parent
  13639. if (parsedLight.parentId) {
  13640. light._waitingParentId = parsedLight.parentId;
  13641. }
  13642. // Animations
  13643. if (parsedLight.animations) {
  13644. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13645. var parsedAnimation = parsedLight.animations[animationIndex];
  13646. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13647. }
  13648. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13649. }
  13650. if (parsedLight.autoAnimate) {
  13651. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13652. }
  13653. return light;
  13654. };
  13655. Light.prototype._hookArrayForExcluded = function (array) {
  13656. var _this = this;
  13657. var oldPush = array.push;
  13658. array.push = function () {
  13659. var items = [];
  13660. for (var _i = 0; _i < arguments.length; _i++) {
  13661. items[_i] = arguments[_i];
  13662. }
  13663. var result = oldPush.apply(array, items);
  13664. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13665. var item = items_1[_a];
  13666. item._resyncLighSource(_this);
  13667. }
  13668. return result;
  13669. };
  13670. var oldSplice = array.splice;
  13671. array.splice = function (index, deleteCount) {
  13672. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13673. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13674. var item = deleted_1[_i];
  13675. item._resyncLighSource(_this);
  13676. }
  13677. return deleted;
  13678. };
  13679. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13680. var item = array_1[_i];
  13681. item._resyncLighSource(this);
  13682. }
  13683. };
  13684. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13685. var _this = this;
  13686. var oldPush = array.push;
  13687. array.push = function () {
  13688. var items = [];
  13689. for (var _i = 0; _i < arguments.length; _i++) {
  13690. items[_i] = arguments[_i];
  13691. }
  13692. var result = oldPush.apply(array, items);
  13693. _this._resyncMeshes();
  13694. return result;
  13695. };
  13696. var oldSplice = array.splice;
  13697. array.splice = function (index, deleteCount) {
  13698. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13699. _this._resyncMeshes();
  13700. return deleted;
  13701. };
  13702. this._resyncMeshes();
  13703. };
  13704. Light.prototype._resyncMeshes = function () {
  13705. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13706. var mesh = _a[_i];
  13707. mesh._resyncLighSource(this);
  13708. }
  13709. };
  13710. Light.prototype._markMeshesAsLightDirty = function () {
  13711. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13712. var mesh = _a[_i];
  13713. if (mesh._lightSources.indexOf(this) !== -1) {
  13714. mesh._markSubMeshesAsLightDirty();
  13715. }
  13716. }
  13717. };
  13718. /**
  13719. * Recomputes the cached photometric scale if needed.
  13720. */
  13721. Light.prototype._computePhotometricScale = function () {
  13722. this._photometricScale = this._getPhotometricScale();
  13723. this.getScene().resetCachedMaterial();
  13724. };
  13725. /**
  13726. * Returns the Photometric Scale according to the light type and intensity mode.
  13727. */
  13728. Light.prototype._getPhotometricScale = function () {
  13729. var photometricScale = 0.0;
  13730. var lightTypeID = this.getTypeID();
  13731. //get photometric mode
  13732. var photometricMode = this.intensityMode;
  13733. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13734. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13735. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13736. }
  13737. else {
  13738. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13739. }
  13740. }
  13741. //compute photometric scale
  13742. switch (lightTypeID) {
  13743. case Light.LIGHTTYPEID_POINTLIGHT:
  13744. case Light.LIGHTTYPEID_SPOTLIGHT:
  13745. switch (photometricMode) {
  13746. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13747. photometricScale = 1.0 / (4.0 * Math.PI);
  13748. break;
  13749. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13750. photometricScale = 1.0;
  13751. break;
  13752. case Light.INTENSITYMODE_LUMINANCE:
  13753. photometricScale = this.radius * this.radius;
  13754. break;
  13755. }
  13756. break;
  13757. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13758. switch (photometricMode) {
  13759. case Light.INTENSITYMODE_ILLUMINANCE:
  13760. photometricScale = 1.0;
  13761. break;
  13762. case Light.INTENSITYMODE_LUMINANCE:
  13763. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13764. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13765. var apexAngleRadians = this.radius;
  13766. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13767. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13768. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13769. photometricScale = solidAngle;
  13770. break;
  13771. }
  13772. break;
  13773. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13774. // No fall off in hemisperic light.
  13775. photometricScale = 1.0;
  13776. break;
  13777. }
  13778. return photometricScale;
  13779. };
  13780. Light.prototype._reorderLightsInScene = function () {
  13781. var scene = this.getScene();
  13782. if (this.renderPriority != 0) {
  13783. scene.requireLightSorting = true;
  13784. }
  13785. this.getScene().sortLightsByPriority();
  13786. };
  13787. return Light;
  13788. }(BABYLON.Node));
  13789. //lightmapMode Consts
  13790. Light._LIGHTMAP_DEFAULT = 0;
  13791. Light._LIGHTMAP_SPECULAR = 1;
  13792. Light._LIGHTMAP_SHADOWSONLY = 2;
  13793. // Intensity Mode Consts
  13794. Light._INTENSITYMODE_AUTOMATIC = 0;
  13795. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13796. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13797. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13798. Light._INTENSITYMODE_LUMINANCE = 4;
  13799. // Light types ids const.
  13800. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13801. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13802. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13803. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13804. __decorate([
  13805. BABYLON.serializeAsColor3()
  13806. ], Light.prototype, "diffuse", void 0);
  13807. __decorate([
  13808. BABYLON.serializeAsColor3()
  13809. ], Light.prototype, "specular", void 0);
  13810. __decorate([
  13811. BABYLON.serialize()
  13812. ], Light.prototype, "intensity", void 0);
  13813. __decorate([
  13814. BABYLON.serialize()
  13815. ], Light.prototype, "range", void 0);
  13816. __decorate([
  13817. BABYLON.serialize()
  13818. ], Light.prototype, "intensityMode", null);
  13819. __decorate([
  13820. BABYLON.serialize()
  13821. ], Light.prototype, "radius", null);
  13822. __decorate([
  13823. BABYLON.serialize()
  13824. ], Light.prototype, "_renderPriority", void 0);
  13825. __decorate([
  13826. BABYLON.expandToProperty("_reorderLightsInScene")
  13827. ], Light.prototype, "renderPriority", void 0);
  13828. __decorate([
  13829. BABYLON.serialize()
  13830. ], Light.prototype, "shadowEnabled", void 0);
  13831. __decorate([
  13832. BABYLON.serialize("excludeWithLayerMask")
  13833. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13834. __decorate([
  13835. BABYLON.serialize("includeOnlyWithLayerMask")
  13836. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13837. __decorate([
  13838. BABYLON.serialize("lightmapMode")
  13839. ], Light.prototype, "_lightmapMode", void 0);
  13840. BABYLON.Light = Light;
  13841. })(BABYLON || (BABYLON = {}));
  13842. //# sourceMappingURL=babylon.light.js.map
  13843. var BABYLON;
  13844. (function (BABYLON) {
  13845. var Camera = (function (_super) {
  13846. __extends(Camera, _super);
  13847. function Camera(name, position, scene) {
  13848. var _this = _super.call(this, name, scene) || this;
  13849. _this.upVector = BABYLON.Vector3.Up();
  13850. _this.orthoLeft = null;
  13851. _this.orthoRight = null;
  13852. _this.orthoBottom = null;
  13853. _this.orthoTop = null;
  13854. _this.fov = 0.8;
  13855. _this.minZ = 1.0;
  13856. _this.maxZ = 10000.0;
  13857. _this.inertia = 0.9;
  13858. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13859. _this.isIntermediate = false;
  13860. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13861. _this.layerMask = 0x0FFFFFFF;
  13862. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13863. // Camera rig members
  13864. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13865. _this._rigCameras = new Array();
  13866. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13867. _this.customRenderTargets = new Array();
  13868. // Cache
  13869. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13870. _this._projectionMatrix = new BABYLON.Matrix();
  13871. _this._doNotComputeProjectionMatrix = false;
  13872. _this._postProcesses = new Array();
  13873. _this._transformMatrix = BABYLON.Matrix.Zero();
  13874. _this._activeMeshes = new BABYLON.SmartArray(256);
  13875. _this._globalPosition = BABYLON.Vector3.Zero();
  13876. _this._refreshFrustumPlanes = true;
  13877. _this.getScene().addCamera(_this);
  13878. if (!_this.getScene().activeCamera) {
  13879. _this.getScene().activeCamera = _this;
  13880. }
  13881. _this.position = position;
  13882. return _this;
  13883. }
  13884. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13885. get: function () {
  13886. return Camera._PERSPECTIVE_CAMERA;
  13887. },
  13888. enumerable: true,
  13889. configurable: true
  13890. });
  13891. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13892. get: function () {
  13893. return Camera._ORTHOGRAPHIC_CAMERA;
  13894. },
  13895. enumerable: true,
  13896. configurable: true
  13897. });
  13898. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13899. get: function () {
  13900. return Camera._FOVMODE_VERTICAL_FIXED;
  13901. },
  13902. enumerable: true,
  13903. configurable: true
  13904. });
  13905. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13906. get: function () {
  13907. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13908. },
  13909. enumerable: true,
  13910. configurable: true
  13911. });
  13912. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13913. get: function () {
  13914. return Camera._RIG_MODE_NONE;
  13915. },
  13916. enumerable: true,
  13917. configurable: true
  13918. });
  13919. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13920. get: function () {
  13921. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13922. },
  13923. enumerable: true,
  13924. configurable: true
  13925. });
  13926. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13927. get: function () {
  13928. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13929. },
  13930. enumerable: true,
  13931. configurable: true
  13932. });
  13933. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13934. get: function () {
  13935. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13936. },
  13937. enumerable: true,
  13938. configurable: true
  13939. });
  13940. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13941. get: function () {
  13942. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13943. },
  13944. enumerable: true,
  13945. configurable: true
  13946. });
  13947. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13948. get: function () {
  13949. return Camera._RIG_MODE_VR;
  13950. },
  13951. enumerable: true,
  13952. configurable: true
  13953. });
  13954. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13955. get: function () {
  13956. return Camera._RIG_MODE_WEBVR;
  13957. },
  13958. enumerable: true,
  13959. configurable: true
  13960. });
  13961. Camera.prototype.getClassName = function () {
  13962. return "Camera";
  13963. };
  13964. /**
  13965. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13966. */
  13967. Camera.prototype.toString = function (fullDetails) {
  13968. var ret = "Name: " + this.name;
  13969. ret += ", type: " + this.getClassName();
  13970. if (this.animations) {
  13971. for (var i = 0; i < this.animations.length; i++) {
  13972. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13973. }
  13974. }
  13975. if (fullDetails) {
  13976. }
  13977. return ret;
  13978. };
  13979. Object.defineProperty(Camera.prototype, "globalPosition", {
  13980. get: function () {
  13981. return this._globalPosition;
  13982. },
  13983. enumerable: true,
  13984. configurable: true
  13985. });
  13986. Camera.prototype.getActiveMeshes = function () {
  13987. return this._activeMeshes;
  13988. };
  13989. Camera.prototype.isActiveMesh = function (mesh) {
  13990. return (this._activeMeshes.indexOf(mesh) !== -1);
  13991. };
  13992. //Cache
  13993. Camera.prototype._initCache = function () {
  13994. _super.prototype._initCache.call(this);
  13995. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13996. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13997. this._cache.mode = undefined;
  13998. this._cache.minZ = undefined;
  13999. this._cache.maxZ = undefined;
  14000. this._cache.fov = undefined;
  14001. this._cache.fovMode = undefined;
  14002. this._cache.aspectRatio = undefined;
  14003. this._cache.orthoLeft = undefined;
  14004. this._cache.orthoRight = undefined;
  14005. this._cache.orthoBottom = undefined;
  14006. this._cache.orthoTop = undefined;
  14007. this._cache.renderWidth = undefined;
  14008. this._cache.renderHeight = undefined;
  14009. };
  14010. Camera.prototype._updateCache = function (ignoreParentClass) {
  14011. if (!ignoreParentClass) {
  14012. _super.prototype._updateCache.call(this);
  14013. }
  14014. var engine = this.getEngine();
  14015. this._cache.position.copyFrom(this.position);
  14016. this._cache.upVector.copyFrom(this.upVector);
  14017. this._cache.mode = this.mode;
  14018. this._cache.minZ = this.minZ;
  14019. this._cache.maxZ = this.maxZ;
  14020. this._cache.fov = this.fov;
  14021. this._cache.fovMode = this.fovMode;
  14022. this._cache.aspectRatio = engine.getAspectRatio(this);
  14023. this._cache.orthoLeft = this.orthoLeft;
  14024. this._cache.orthoRight = this.orthoRight;
  14025. this._cache.orthoBottom = this.orthoBottom;
  14026. this._cache.orthoTop = this.orthoTop;
  14027. this._cache.renderWidth = engine.getRenderWidth();
  14028. this._cache.renderHeight = engine.getRenderHeight();
  14029. };
  14030. Camera.prototype._updateFromScene = function () {
  14031. this.updateCache();
  14032. this.update();
  14033. };
  14034. // Synchronized
  14035. Camera.prototype._isSynchronized = function () {
  14036. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14037. };
  14038. Camera.prototype._isSynchronizedViewMatrix = function () {
  14039. if (!_super.prototype._isSynchronized.call(this))
  14040. return false;
  14041. return this._cache.position.equals(this.position)
  14042. && this._cache.upVector.equals(this.upVector)
  14043. && this.isSynchronizedWithParent();
  14044. };
  14045. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14046. var check = this._cache.mode === this.mode
  14047. && this._cache.minZ === this.minZ
  14048. && this._cache.maxZ === this.maxZ;
  14049. if (!check) {
  14050. return false;
  14051. }
  14052. var engine = this.getEngine();
  14053. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14054. check = this._cache.fov === this.fov
  14055. && this._cache.fovMode === this.fovMode
  14056. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14057. }
  14058. else {
  14059. check = this._cache.orthoLeft === this.orthoLeft
  14060. && this._cache.orthoRight === this.orthoRight
  14061. && this._cache.orthoBottom === this.orthoBottom
  14062. && this._cache.orthoTop === this.orthoTop
  14063. && this._cache.renderWidth === engine.getRenderWidth()
  14064. && this._cache.renderHeight === engine.getRenderHeight();
  14065. }
  14066. return check;
  14067. };
  14068. // Controls
  14069. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14070. };
  14071. Camera.prototype.detachControl = function (element) {
  14072. };
  14073. Camera.prototype.update = function () {
  14074. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14075. this._updateRigCameras();
  14076. }
  14077. this._checkInputs();
  14078. };
  14079. Camera.prototype._checkInputs = function () {
  14080. };
  14081. Object.defineProperty(Camera.prototype, "rigCameras", {
  14082. get: function () {
  14083. return this._rigCameras;
  14084. },
  14085. enumerable: true,
  14086. configurable: true
  14087. });
  14088. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14089. get: function () {
  14090. return this._rigPostProcess;
  14091. },
  14092. enumerable: true,
  14093. configurable: true
  14094. });
  14095. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14096. // invalidate framebuffer
  14097. if (this._postProcesses.length > 0) {
  14098. this._postProcesses[0].markTextureDirty();
  14099. }
  14100. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14101. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14102. var cam = this._rigCameras[i];
  14103. var rigPostProcess = cam._rigPostProcess;
  14104. // for VR rig, there does not have to be a post process
  14105. if (rigPostProcess) {
  14106. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14107. if (isPass) {
  14108. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14109. cam.isIntermediate = this._postProcesses.length === 0;
  14110. }
  14111. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14112. rigPostProcess.markTextureDirty();
  14113. }
  14114. else {
  14115. cam._postProcesses = this._postProcesses.slice(0);
  14116. }
  14117. }
  14118. };
  14119. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14120. if (insertAt === void 0) { insertAt = null; }
  14121. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14122. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14123. return 0;
  14124. }
  14125. if (insertAt == null || insertAt < 0) {
  14126. this._postProcesses.push(postProcess);
  14127. }
  14128. else {
  14129. this._postProcesses.splice(insertAt, 0, postProcess);
  14130. }
  14131. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14132. return this._postProcesses.indexOf(postProcess);
  14133. };
  14134. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14135. if (atIndices === void 0) { atIndices = null; }
  14136. var result = [];
  14137. var i;
  14138. var index;
  14139. if (!atIndices) {
  14140. var idx = this._postProcesses.indexOf(postProcess);
  14141. if (idx !== -1) {
  14142. this._postProcesses.splice(idx, 1);
  14143. }
  14144. }
  14145. else {
  14146. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14147. // iterate descending, so can just splice as we go
  14148. for (i = atIndices.length - 1; i >= 0; i--) {
  14149. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14150. result.push(i);
  14151. continue;
  14152. }
  14153. index = atIndices[i];
  14154. this._postProcesses.splice(index, 1);
  14155. }
  14156. }
  14157. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14158. return result;
  14159. };
  14160. Camera.prototype.getWorldMatrix = function () {
  14161. if (!this._worldMatrix) {
  14162. this._worldMatrix = BABYLON.Matrix.Identity();
  14163. }
  14164. var viewMatrix = this.getViewMatrix();
  14165. viewMatrix.invertToRef(this._worldMatrix);
  14166. return this._worldMatrix;
  14167. };
  14168. Camera.prototype._getViewMatrix = function () {
  14169. return BABYLON.Matrix.Identity();
  14170. };
  14171. Camera.prototype.getViewMatrix = function (force) {
  14172. this._computedViewMatrix = this._computeViewMatrix(force);
  14173. if (!force && this._isSynchronizedViewMatrix()) {
  14174. return this._computedViewMatrix;
  14175. }
  14176. this._refreshFrustumPlanes = true;
  14177. if (!this.parent || !this.parent.getWorldMatrix) {
  14178. this._globalPosition.copyFrom(this.position);
  14179. }
  14180. else {
  14181. if (!this._worldMatrix) {
  14182. this._worldMatrix = BABYLON.Matrix.Identity();
  14183. }
  14184. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14185. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14186. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14187. this._computedViewMatrix.invert();
  14188. this._markSyncedWithParent();
  14189. }
  14190. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14191. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14192. }
  14193. this._currentRenderId = this.getScene().getRenderId();
  14194. return this._computedViewMatrix;
  14195. };
  14196. Camera.prototype._computeViewMatrix = function (force) {
  14197. if (!force && this._isSynchronizedViewMatrix()) {
  14198. return this._computedViewMatrix;
  14199. }
  14200. this._computedViewMatrix = this._getViewMatrix();
  14201. this._currentRenderId = this.getScene().getRenderId();
  14202. return this._computedViewMatrix;
  14203. };
  14204. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14205. this._doNotComputeProjectionMatrix = true;
  14206. if (projection !== undefined) {
  14207. this._projectionMatrix = projection;
  14208. }
  14209. };
  14210. ;
  14211. Camera.prototype.unfreezeProjectionMatrix = function () {
  14212. this._doNotComputeProjectionMatrix = false;
  14213. };
  14214. ;
  14215. Camera.prototype.getProjectionMatrix = function (force) {
  14216. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14217. return this._projectionMatrix;
  14218. }
  14219. this._refreshFrustumPlanes = true;
  14220. var engine = this.getEngine();
  14221. var scene = this.getScene();
  14222. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14223. if (this.minZ <= 0) {
  14224. this.minZ = 0.1;
  14225. }
  14226. if (scene.useRightHandedSystem) {
  14227. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14228. }
  14229. else {
  14230. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14231. }
  14232. return this._projectionMatrix;
  14233. }
  14234. var halfWidth = engine.getRenderWidth() / 2.0;
  14235. var halfHeight = engine.getRenderHeight() / 2.0;
  14236. if (scene.useRightHandedSystem) {
  14237. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14238. }
  14239. else {
  14240. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14241. }
  14242. return this._projectionMatrix;
  14243. };
  14244. Camera.prototype.getTranformationMatrix = function () {
  14245. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14246. return this._transformMatrix;
  14247. };
  14248. Camera.prototype.updateFrustumPlanes = function () {
  14249. if (!this._refreshFrustumPlanes) {
  14250. return;
  14251. }
  14252. this.getTranformationMatrix();
  14253. if (!this._frustumPlanes) {
  14254. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14255. }
  14256. else {
  14257. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14258. }
  14259. this._refreshFrustumPlanes = false;
  14260. };
  14261. Camera.prototype.isInFrustum = function (target) {
  14262. this.updateFrustumPlanes();
  14263. return target.isInFrustum(this._frustumPlanes);
  14264. };
  14265. Camera.prototype.isCompletelyInFrustum = function (target) {
  14266. this.updateFrustumPlanes();
  14267. return target.isCompletelyInFrustum(this._frustumPlanes);
  14268. };
  14269. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14270. if (length === void 0) { length = 100; }
  14271. if (!transform) {
  14272. transform = this.getWorldMatrix();
  14273. }
  14274. if (!origin) {
  14275. origin = this.position;
  14276. }
  14277. var forward = new BABYLON.Vector3(0, 0, 1);
  14278. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14279. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14280. return new BABYLON.Ray(origin, direction, length);
  14281. };
  14282. Camera.prototype.dispose = function () {
  14283. // Animations
  14284. this.getScene().stopAnimation(this);
  14285. // Remove from scene
  14286. this.getScene().removeCamera(this);
  14287. while (this._rigCameras.length > 0) {
  14288. this._rigCameras.pop().dispose();
  14289. }
  14290. // Postprocesses
  14291. var i = this._postProcesses.length;
  14292. while (--i >= 0) {
  14293. this._postProcesses[i].dispose(this);
  14294. }
  14295. _super.prototype.dispose.call(this);
  14296. };
  14297. Object.defineProperty(Camera.prototype, "leftCamera", {
  14298. // ---- Camera rigs section ----
  14299. get: function () {
  14300. if (this._rigCameras.length < 1) {
  14301. return undefined;
  14302. }
  14303. return this._rigCameras[0];
  14304. },
  14305. enumerable: true,
  14306. configurable: true
  14307. });
  14308. Object.defineProperty(Camera.prototype, "rightCamera", {
  14309. get: function () {
  14310. if (this._rigCameras.length < 2) {
  14311. return undefined;
  14312. }
  14313. return this._rigCameras[1];
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. Camera.prototype.getLeftTarget = function () {
  14319. if (this._rigCameras.length < 1) {
  14320. return undefined;
  14321. }
  14322. return this._rigCameras[0].getTarget();
  14323. };
  14324. Camera.prototype.getRightTarget = function () {
  14325. if (this._rigCameras.length < 2) {
  14326. return undefined;
  14327. }
  14328. return this._rigCameras[1].getTarget();
  14329. };
  14330. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14331. while (this._rigCameras.length > 0) {
  14332. this._rigCameras.pop().dispose();
  14333. }
  14334. this.cameraRigMode = mode;
  14335. this._cameraRigParams = {};
  14336. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14337. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14338. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14339. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14340. // create the rig cameras, unless none
  14341. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14342. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14343. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14344. }
  14345. switch (this.cameraRigMode) {
  14346. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14347. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14348. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14349. break;
  14350. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14351. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14352. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14353. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14354. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14355. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14356. break;
  14357. case Camera.RIG_MODE_VR:
  14358. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14359. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14360. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14361. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14362. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14363. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14364. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14365. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14366. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14367. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14368. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14369. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14370. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14371. if (metrics.compensateDistortion) {
  14372. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14373. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14374. }
  14375. break;
  14376. case Camera.RIG_MODE_WEBVR:
  14377. if (rigParams.vrDisplay) {
  14378. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14379. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14380. //Left eye
  14381. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14382. this._rigCameras[0].setCameraRigParameter("left", true);
  14383. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14384. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14385. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14386. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14387. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14388. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14389. this._rigCameras[0].parent = this;
  14390. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14391. //Right eye
  14392. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14393. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14394. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14395. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14396. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14397. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14398. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14399. this._rigCameras[1].parent = this;
  14400. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14401. }
  14402. break;
  14403. }
  14404. this._cascadePostProcessesToRigCams();
  14405. this.
  14406. update();
  14407. };
  14408. Camera.prototype._getVRProjectionMatrix = function () {
  14409. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14410. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14411. return this._projectionMatrix;
  14412. };
  14413. Camera.prototype._updateCameraRotationMatrix = function () {
  14414. //Here for WebVR
  14415. };
  14416. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14417. //Here for WebVR
  14418. };
  14419. /**
  14420. * This function MUST be overwritten by the different WebVR cameras available.
  14421. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14422. */
  14423. Camera.prototype._getWebVRProjectionMatrix = function () {
  14424. return BABYLON.Matrix.Identity();
  14425. };
  14426. /**
  14427. * This function MUST be overwritten by the different WebVR cameras available.
  14428. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14429. */
  14430. Camera.prototype._getWebVRViewMatrix = function () {
  14431. return BABYLON.Matrix.Identity();
  14432. };
  14433. Camera.prototype.setCameraRigParameter = function (name, value) {
  14434. if (!this._cameraRigParams) {
  14435. this._cameraRigParams = {};
  14436. }
  14437. this._cameraRigParams[name] = value;
  14438. //provisionnally:
  14439. if (name === "interaxialDistance") {
  14440. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14441. }
  14442. };
  14443. /**
  14444. * needs to be overridden by children so sub has required properties to be copied
  14445. */
  14446. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14447. return null;
  14448. };
  14449. /**
  14450. * May need to be overridden by children
  14451. */
  14452. Camera.prototype._updateRigCameras = function () {
  14453. for (var i = 0; i < this._rigCameras.length; i++) {
  14454. this._rigCameras[i].minZ = this.minZ;
  14455. this._rigCameras[i].maxZ = this.maxZ;
  14456. this._rigCameras[i].fov = this.fov;
  14457. }
  14458. // only update viewport when ANAGLYPH
  14459. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14460. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14461. }
  14462. };
  14463. Camera.prototype._setupInputs = function () {
  14464. };
  14465. Camera.prototype.serialize = function () {
  14466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14467. // Type
  14468. serializationObject.type = this.getClassName();
  14469. // Parent
  14470. if (this.parent) {
  14471. serializationObject.parentId = this.parent.id;
  14472. }
  14473. if (this.inputs) {
  14474. this.inputs.serialize(serializationObject);
  14475. }
  14476. // Animations
  14477. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14478. serializationObject.ranges = this.serializeAnimationRanges();
  14479. return serializationObject;
  14480. };
  14481. Camera.prototype.clone = function (name) {
  14482. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14483. };
  14484. Camera.prototype.getDirection = function (localAxis) {
  14485. var result = BABYLON.Vector3.Zero();
  14486. this.getDirectionToRef(localAxis, result);
  14487. return result;
  14488. };
  14489. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14490. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14491. };
  14492. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14493. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14494. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14495. switch (type) {
  14496. case "ArcRotateCamera":
  14497. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14498. case "DeviceOrientationCamera":
  14499. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14500. case "FollowCamera":
  14501. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14502. case "ArcFollowCamera":
  14503. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14504. case "GamepadCamera":
  14505. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14506. case "TouchCamera":
  14507. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14508. case "VirtualJoysticksCamera":
  14509. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14510. case "WebVRFreeCamera":
  14511. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14512. case "WebVRGamepadCamera":
  14513. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14514. case "VRDeviceOrientationFreeCamera":
  14515. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14516. case "VRDeviceOrientationGamepadCamera":
  14517. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14518. case "AnaglyphArcRotateCamera":
  14519. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14520. case "AnaglyphFreeCamera":
  14521. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14522. case "AnaglyphGamepadCamera":
  14523. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14524. case "AnaglyphUniversalCamera":
  14525. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14526. case "StereoscopicArcRotateCamera":
  14527. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14528. case "StereoscopicFreeCamera":
  14529. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14530. case "StereoscopicGamepadCamera":
  14531. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14532. case "StereoscopicUniversalCamera":
  14533. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14534. case "FreeCamera":
  14535. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14536. default:
  14537. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14538. }
  14539. };
  14540. Camera.Parse = function (parsedCamera, scene) {
  14541. var type = parsedCamera.type;
  14542. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14543. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14544. // Parent
  14545. if (parsedCamera.parentId) {
  14546. camera._waitingParentId = parsedCamera.parentId;
  14547. }
  14548. //If camera has an input manager, let it parse inputs settings
  14549. if (camera.inputs) {
  14550. camera.inputs.parse(parsedCamera);
  14551. camera._setupInputs();
  14552. }
  14553. if (camera.setPosition) {
  14554. camera.position.copyFromFloats(0, 0, 0);
  14555. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14556. }
  14557. // Target
  14558. if (parsedCamera.target) {
  14559. if (camera.setTarget) {
  14560. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14561. }
  14562. }
  14563. // Apply 3d rig, when found
  14564. if (parsedCamera.cameraRigMode) {
  14565. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14566. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14567. }
  14568. // Animations
  14569. if (parsedCamera.animations) {
  14570. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14571. var parsedAnimation = parsedCamera.animations[animationIndex];
  14572. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14573. }
  14574. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14575. }
  14576. if (parsedCamera.autoAnimate) {
  14577. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14578. }
  14579. return camera;
  14580. };
  14581. return Camera;
  14582. }(BABYLON.Node));
  14583. // Statics
  14584. Camera._PERSPECTIVE_CAMERA = 0;
  14585. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14586. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14587. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14588. Camera._RIG_MODE_NONE = 0;
  14589. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14590. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14591. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14592. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14593. Camera._RIG_MODE_VR = 20;
  14594. Camera._RIG_MODE_WEBVR = 21;
  14595. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14596. __decorate([
  14597. BABYLON.serializeAsVector3()
  14598. ], Camera.prototype, "position", void 0);
  14599. __decorate([
  14600. BABYLON.serializeAsVector3()
  14601. ], Camera.prototype, "upVector", void 0);
  14602. __decorate([
  14603. BABYLON.serialize()
  14604. ], Camera.prototype, "orthoLeft", void 0);
  14605. __decorate([
  14606. BABYLON.serialize()
  14607. ], Camera.prototype, "orthoRight", void 0);
  14608. __decorate([
  14609. BABYLON.serialize()
  14610. ], Camera.prototype, "orthoBottom", void 0);
  14611. __decorate([
  14612. BABYLON.serialize()
  14613. ], Camera.prototype, "orthoTop", void 0);
  14614. __decorate([
  14615. BABYLON.serialize()
  14616. ], Camera.prototype, "fov", void 0);
  14617. __decorate([
  14618. BABYLON.serialize()
  14619. ], Camera.prototype, "minZ", void 0);
  14620. __decorate([
  14621. BABYLON.serialize()
  14622. ], Camera.prototype, "maxZ", void 0);
  14623. __decorate([
  14624. BABYLON.serialize()
  14625. ], Camera.prototype, "inertia", void 0);
  14626. __decorate([
  14627. BABYLON.serialize()
  14628. ], Camera.prototype, "mode", void 0);
  14629. __decorate([
  14630. BABYLON.serialize()
  14631. ], Camera.prototype, "layerMask", void 0);
  14632. __decorate([
  14633. BABYLON.serialize()
  14634. ], Camera.prototype, "fovMode", void 0);
  14635. __decorate([
  14636. BABYLON.serialize()
  14637. ], Camera.prototype, "cameraRigMode", void 0);
  14638. __decorate([
  14639. BABYLON.serialize()
  14640. ], Camera.prototype, "interaxialDistance", void 0);
  14641. __decorate([
  14642. BABYLON.serialize()
  14643. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14644. BABYLON.Camera = Camera;
  14645. })(BABYLON || (BABYLON = {}));
  14646. //# sourceMappingURL=babylon.camera.js.map
  14647. var BABYLON;
  14648. (function (BABYLON) {
  14649. var RenderingManager = (function () {
  14650. function RenderingManager(scene) {
  14651. this._renderingGroups = new Array();
  14652. this._autoClearDepthStencil = {};
  14653. this._customOpaqueSortCompareFn = {};
  14654. this._customAlphaTestSortCompareFn = {};
  14655. this._customTransparentSortCompareFn = {};
  14656. this._renderinGroupInfo = null;
  14657. this._scene = scene;
  14658. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14659. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14660. }
  14661. }
  14662. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14663. if (depth === void 0) { depth = true; }
  14664. if (stencil === void 0) { stencil = true; }
  14665. if (this._depthStencilBufferAlreadyCleaned) {
  14666. return;
  14667. }
  14668. this._scene.getEngine().clear(null, false, depth, stencil);
  14669. this._depthStencilBufferAlreadyCleaned = true;
  14670. };
  14671. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14672. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14673. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14674. var info = null;
  14675. if (observable) {
  14676. if (!this._renderinGroupInfo) {
  14677. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14678. }
  14679. info = this._renderinGroupInfo;
  14680. info.scene = this._scene;
  14681. info.camera = this._scene.activeCamera;
  14682. }
  14683. // Dispatch sprites
  14684. if (renderSprites) {
  14685. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14686. var manager = this._scene.spriteManagers[index];
  14687. this.dispatchSprites(manager);
  14688. }
  14689. }
  14690. // Render
  14691. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14692. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14693. var renderingGroup = this._renderingGroups[index];
  14694. if (!renderingGroup && !observable)
  14695. continue;
  14696. this._currentIndex = index;
  14697. var renderingGroupMask = 0;
  14698. // Fire PRECLEAR stage
  14699. if (observable) {
  14700. renderingGroupMask = Math.pow(2, index);
  14701. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14702. info.renderingGroupId = index;
  14703. observable.notifyObservers(info, renderingGroupMask);
  14704. }
  14705. // Clear depth/stencil if needed
  14706. if (RenderingManager.AUTOCLEAR) {
  14707. var autoClear = this._autoClearDepthStencil[index];
  14708. if (autoClear && autoClear.autoClear) {
  14709. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14710. }
  14711. }
  14712. if (observable) {
  14713. // Fire PREOPAQUE stage
  14714. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14715. observable.notifyObservers(info, renderingGroupMask);
  14716. // Fire PRETRANSPARENT stage
  14717. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14718. observable.notifyObservers(info, renderingGroupMask);
  14719. }
  14720. if (renderingGroup)
  14721. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14722. // Fire POSTTRANSPARENT stage
  14723. if (observable) {
  14724. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14725. observable.notifyObservers(info, renderingGroupMask);
  14726. }
  14727. }
  14728. };
  14729. RenderingManager.prototype.reset = function () {
  14730. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14731. var renderingGroup = this._renderingGroups[index];
  14732. if (renderingGroup) {
  14733. renderingGroup.prepare();
  14734. }
  14735. }
  14736. };
  14737. RenderingManager.prototype.dispose = function () {
  14738. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14739. var renderingGroup = this._renderingGroups[index];
  14740. if (renderingGroup) {
  14741. renderingGroup.dispose();
  14742. }
  14743. }
  14744. this._renderingGroups.length = 0;
  14745. };
  14746. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14747. if (!this._renderingGroups[renderingGroupId]) {
  14748. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14749. }
  14750. };
  14751. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14752. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14753. this._prepareRenderingGroup(renderingGroupId);
  14754. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14755. };
  14756. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14757. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14758. this._prepareRenderingGroup(renderingGroupId);
  14759. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14760. };
  14761. RenderingManager.prototype.dispatch = function (subMesh) {
  14762. var mesh = subMesh.getMesh();
  14763. var renderingGroupId = mesh.renderingGroupId || 0;
  14764. this._prepareRenderingGroup(renderingGroupId);
  14765. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14766. };
  14767. /**
  14768. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14769. * This allowed control for front to back rendering or reversly depending of the special needs.
  14770. *
  14771. * @param renderingGroupId The rendering group id corresponding to its index
  14772. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14773. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14774. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14775. */
  14776. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14777. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14778. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14779. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14780. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14781. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14782. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14783. if (this._renderingGroups[renderingGroupId]) {
  14784. var group = this._renderingGroups[renderingGroupId];
  14785. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14786. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14787. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14788. }
  14789. };
  14790. /**
  14791. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14792. *
  14793. * @param renderingGroupId The rendering group id corresponding to its index
  14794. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14795. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14796. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14797. */
  14798. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14799. if (depth === void 0) { depth = true; }
  14800. if (stencil === void 0) { stencil = true; }
  14801. this._autoClearDepthStencil[renderingGroupId] = {
  14802. autoClear: autoClearDepthStencil,
  14803. depth: depth,
  14804. stencil: stencil
  14805. };
  14806. };
  14807. return RenderingManager;
  14808. }());
  14809. /**
  14810. * The max id used for rendering groups (not included)
  14811. */
  14812. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14813. /**
  14814. * The min id used for rendering groups (included)
  14815. */
  14816. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14817. /**
  14818. * Used to globally prevent autoclearing scenes.
  14819. */
  14820. RenderingManager.AUTOCLEAR = true;
  14821. BABYLON.RenderingManager = RenderingManager;
  14822. })(BABYLON || (BABYLON = {}));
  14823. //# sourceMappingURL=babylon.renderingManager.js.map
  14824. var BABYLON;
  14825. (function (BABYLON) {
  14826. var RenderingGroup = (function () {
  14827. /**
  14828. * Creates a new rendering group.
  14829. * @param index The rendering group index
  14830. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14831. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14832. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14833. */
  14834. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14835. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14836. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14837. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14838. this.index = index;
  14839. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14840. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14841. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14842. this._particleSystems = new BABYLON.SmartArray(256);
  14843. this._spriteManagers = new BABYLON.SmartArray(256);
  14844. this._edgesRenderers = new BABYLON.SmartArray(16);
  14845. this._scene = scene;
  14846. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14847. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14848. this.transparentSortCompareFn = transparentSortCompareFn;
  14849. }
  14850. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14851. /**
  14852. * Set the opaque sort comparison function.
  14853. * If null the sub meshes will be render in the order they were created
  14854. */
  14855. set: function (value) {
  14856. this._opaqueSortCompareFn = value;
  14857. if (value) {
  14858. this._renderOpaque = this.renderOpaqueSorted;
  14859. }
  14860. else {
  14861. this._renderOpaque = RenderingGroup.renderUnsorted;
  14862. }
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14868. /**
  14869. * Set the alpha test sort comparison function.
  14870. * If null the sub meshes will be render in the order they were created
  14871. */
  14872. set: function (value) {
  14873. this._alphaTestSortCompareFn = value;
  14874. if (value) {
  14875. this._renderAlphaTest = this.renderAlphaTestSorted;
  14876. }
  14877. else {
  14878. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14879. }
  14880. },
  14881. enumerable: true,
  14882. configurable: true
  14883. });
  14884. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14885. /**
  14886. * Set the transparent sort comparison function.
  14887. * If null the sub meshes will be render in the order they were created
  14888. */
  14889. set: function (value) {
  14890. if (value) {
  14891. this._transparentSortCompareFn = value;
  14892. }
  14893. else {
  14894. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14895. }
  14896. this._renderTransparent = this.renderTransparentSorted;
  14897. },
  14898. enumerable: true,
  14899. configurable: true
  14900. });
  14901. /**
  14902. * Render all the sub meshes contained in the group.
  14903. * @param customRenderFunction Used to override the default render behaviour of the group.
  14904. * @returns true if rendered some submeshes.
  14905. */
  14906. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14907. if (customRenderFunction) {
  14908. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14909. return;
  14910. }
  14911. var engine = this._scene.getEngine();
  14912. // Opaque
  14913. if (this._opaqueSubMeshes.length !== 0) {
  14914. this._renderOpaque(this._opaqueSubMeshes);
  14915. }
  14916. // Alpha test
  14917. if (this._alphaTestSubMeshes.length !== 0) {
  14918. engine.setAlphaTesting(true);
  14919. this._renderAlphaTest(this._alphaTestSubMeshes);
  14920. engine.setAlphaTesting(false);
  14921. }
  14922. var stencilState = engine.getStencilBuffer();
  14923. engine.setStencilBuffer(false);
  14924. // Sprites
  14925. if (renderSprites) {
  14926. this._renderSprites();
  14927. }
  14928. // Particles
  14929. if (renderParticles) {
  14930. this._renderParticles(activeMeshes);
  14931. }
  14932. if (this.onBeforeTransparentRendering) {
  14933. this.onBeforeTransparentRendering();
  14934. }
  14935. // Transparent
  14936. if (this._transparentSubMeshes.length !== 0) {
  14937. this._renderTransparent(this._transparentSubMeshes);
  14938. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14939. }
  14940. engine.setStencilBuffer(stencilState);
  14941. // Edges
  14942. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14943. this._edgesRenderers.data[edgesRendererIndex].render();
  14944. }
  14945. };
  14946. /**
  14947. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14948. * @param subMeshes The submeshes to render
  14949. */
  14950. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14951. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14952. };
  14953. /**
  14954. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14955. * @param subMeshes The submeshes to render
  14956. */
  14957. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14958. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14959. };
  14960. /**
  14961. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14962. * @param subMeshes The submeshes to render
  14963. */
  14964. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14965. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14966. };
  14967. /**
  14968. * Renders the submeshes in a specified order.
  14969. * @param subMeshes The submeshes to sort before render
  14970. * @param sortCompareFn The comparison function use to sort
  14971. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14972. * @param transparent Specifies to activate blending if true
  14973. */
  14974. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14975. var subIndex = 0;
  14976. var subMesh;
  14977. for (; subIndex < subMeshes.length; subIndex++) {
  14978. subMesh = subMeshes.data[subIndex];
  14979. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14980. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14981. }
  14982. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14983. sortedArray.sort(sortCompareFn);
  14984. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14985. subMesh = sortedArray[subIndex];
  14986. subMesh.render(transparent);
  14987. }
  14988. };
  14989. /**
  14990. * Renders the submeshes in the order they were dispatched (no sort applied).
  14991. * @param subMeshes The submeshes to render
  14992. */
  14993. RenderingGroup.renderUnsorted = function (subMeshes) {
  14994. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14995. var submesh = subMeshes.data[subIndex];
  14996. submesh.render(false);
  14997. }
  14998. };
  14999. /**
  15000. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15001. * are rendered back to front if in the same alpha index.
  15002. *
  15003. * @param a The first submesh
  15004. * @param b The second submesh
  15005. * @returns The result of the comparison
  15006. */
  15007. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15008. // Alpha index first
  15009. if (a._alphaIndex > b._alphaIndex) {
  15010. return 1;
  15011. }
  15012. if (a._alphaIndex < b._alphaIndex) {
  15013. return -1;
  15014. }
  15015. // Then distance to camera
  15016. return RenderingGroup.backToFrontSortCompare(a, b);
  15017. };
  15018. /**
  15019. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15020. * are rendered back to front.
  15021. *
  15022. * @param a The first submesh
  15023. * @param b The second submesh
  15024. * @returns The result of the comparison
  15025. */
  15026. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15027. // Then distance to camera
  15028. if (a._distanceToCamera < b._distanceToCamera) {
  15029. return 1;
  15030. }
  15031. if (a._distanceToCamera > b._distanceToCamera) {
  15032. return -1;
  15033. }
  15034. return 0;
  15035. };
  15036. /**
  15037. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15038. * are rendered front to back (prevent overdraw).
  15039. *
  15040. * @param a The first submesh
  15041. * @param b The second submesh
  15042. * @returns The result of the comparison
  15043. */
  15044. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15045. // Then distance to camera
  15046. if (a._distanceToCamera < b._distanceToCamera) {
  15047. return -1;
  15048. }
  15049. if (a._distanceToCamera > b._distanceToCamera) {
  15050. return 1;
  15051. }
  15052. return 0;
  15053. };
  15054. /**
  15055. * Resets the different lists of submeshes to prepare a new frame.
  15056. */
  15057. RenderingGroup.prototype.prepare = function () {
  15058. this._opaqueSubMeshes.reset();
  15059. this._transparentSubMeshes.reset();
  15060. this._alphaTestSubMeshes.reset();
  15061. this._particleSystems.reset();
  15062. this._spriteManagers.reset();
  15063. this._edgesRenderers.reset();
  15064. };
  15065. RenderingGroup.prototype.dispose = function () {
  15066. this._opaqueSubMeshes.dispose();
  15067. this._transparentSubMeshes.dispose();
  15068. this._alphaTestSubMeshes.dispose();
  15069. this._particleSystems.dispose();
  15070. this._spriteManagers.dispose();
  15071. this._edgesRenderers.dispose();
  15072. };
  15073. /**
  15074. * Inserts the submesh in its correct queue depending on its material.
  15075. * @param subMesh The submesh to dispatch
  15076. */
  15077. RenderingGroup.prototype.dispatch = function (subMesh) {
  15078. var material = subMesh.getMaterial();
  15079. var mesh = subMesh.getMesh();
  15080. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15081. this._transparentSubMeshes.push(subMesh);
  15082. }
  15083. else if (material.needAlphaTesting()) {
  15084. this._alphaTestSubMeshes.push(subMesh);
  15085. }
  15086. else {
  15087. this._opaqueSubMeshes.push(subMesh); // Opaque
  15088. }
  15089. if (mesh._edgesRenderer) {
  15090. this._edgesRenderers.push(mesh._edgesRenderer);
  15091. }
  15092. };
  15093. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15094. this._spriteManagers.push(spriteManager);
  15095. };
  15096. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15097. this._particleSystems.push(particleSystem);
  15098. };
  15099. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15100. if (this._particleSystems.length === 0) {
  15101. return;
  15102. }
  15103. // Particles
  15104. var activeCamera = this._scene.activeCamera;
  15105. this._scene._particlesDuration.beginMonitoring();
  15106. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15107. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15108. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15109. continue;
  15110. }
  15111. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15112. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15113. }
  15114. }
  15115. this._scene._particlesDuration.endMonitoring(false);
  15116. };
  15117. RenderingGroup.prototype._renderSprites = function () {
  15118. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15119. return;
  15120. }
  15121. // Sprites
  15122. var activeCamera = this._scene.activeCamera;
  15123. this._scene._spritesDuration.beginMonitoring();
  15124. for (var id = 0; id < this._spriteManagers.length; id++) {
  15125. var spriteManager = this._spriteManagers.data[id];
  15126. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15127. spriteManager.render();
  15128. }
  15129. }
  15130. this._scene._spritesDuration.endMonitoring(false);
  15131. };
  15132. return RenderingGroup;
  15133. }());
  15134. BABYLON.RenderingGroup = RenderingGroup;
  15135. })(BABYLON || (BABYLON = {}));
  15136. //# sourceMappingURL=babylon.renderingGroup.js.map
  15137. var BABYLON;
  15138. (function (BABYLON) {
  15139. var ClickInfo = (function () {
  15140. function ClickInfo() {
  15141. this._singleClick = false;
  15142. this._doubleClick = false;
  15143. this._hasSwiped = false;
  15144. this._ignore = false;
  15145. }
  15146. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15147. get: function () {
  15148. return this._singleClick;
  15149. },
  15150. set: function (b) {
  15151. this._singleClick = b;
  15152. },
  15153. enumerable: true,
  15154. configurable: true
  15155. });
  15156. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15157. get: function () {
  15158. return this._doubleClick;
  15159. },
  15160. set: function (b) {
  15161. this._doubleClick = b;
  15162. },
  15163. enumerable: true,
  15164. configurable: true
  15165. });
  15166. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15167. get: function () {
  15168. return this._hasSwiped;
  15169. },
  15170. set: function (b) {
  15171. this._hasSwiped = b;
  15172. },
  15173. enumerable: true,
  15174. configurable: true
  15175. });
  15176. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15177. get: function () {
  15178. return this._ignore;
  15179. },
  15180. set: function (b) {
  15181. this._ignore = b;
  15182. },
  15183. enumerable: true,
  15184. configurable: true
  15185. });
  15186. return ClickInfo;
  15187. }());
  15188. var PointerEventTypes = (function () {
  15189. function PointerEventTypes() {
  15190. }
  15191. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15192. get: function () {
  15193. return PointerEventTypes._POINTERDOWN;
  15194. },
  15195. enumerable: true,
  15196. configurable: true
  15197. });
  15198. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15199. get: function () {
  15200. return PointerEventTypes._POINTERUP;
  15201. },
  15202. enumerable: true,
  15203. configurable: true
  15204. });
  15205. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15206. get: function () {
  15207. return PointerEventTypes._POINTERMOVE;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15213. get: function () {
  15214. return PointerEventTypes._POINTERWHEEL;
  15215. },
  15216. enumerable: true,
  15217. configurable: true
  15218. });
  15219. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15220. get: function () {
  15221. return PointerEventTypes._POINTERPICK;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15227. get: function () {
  15228. return PointerEventTypes._POINTERTAP;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15234. get: function () {
  15235. return PointerEventTypes._POINTERDOUBLETAP;
  15236. },
  15237. enumerable: true,
  15238. configurable: true
  15239. });
  15240. return PointerEventTypes;
  15241. }());
  15242. PointerEventTypes._POINTERDOWN = 0x01;
  15243. PointerEventTypes._POINTERUP = 0x02;
  15244. PointerEventTypes._POINTERMOVE = 0x04;
  15245. PointerEventTypes._POINTERWHEEL = 0x08;
  15246. PointerEventTypes._POINTERPICK = 0x10;
  15247. PointerEventTypes._POINTERTAP = 0x20;
  15248. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15249. BABYLON.PointerEventTypes = PointerEventTypes;
  15250. var PointerInfoBase = (function () {
  15251. function PointerInfoBase(type, event) {
  15252. this.type = type;
  15253. this.event = event;
  15254. }
  15255. return PointerInfoBase;
  15256. }());
  15257. BABYLON.PointerInfoBase = PointerInfoBase;
  15258. /**
  15259. * This class is used to store pointer related info for the onPrePointerObservable event.
  15260. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15261. */
  15262. var PointerInfoPre = (function (_super) {
  15263. __extends(PointerInfoPre, _super);
  15264. function PointerInfoPre(type, event, localX, localY) {
  15265. var _this = _super.call(this, type, event) || this;
  15266. _this.skipOnPointerObservable = false;
  15267. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15268. return _this;
  15269. }
  15270. return PointerInfoPre;
  15271. }(PointerInfoBase));
  15272. BABYLON.PointerInfoPre = PointerInfoPre;
  15273. /**
  15274. * This type contains all the data related to a pointer event in Babylon.js.
  15275. * 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.
  15276. */
  15277. var PointerInfo = (function (_super) {
  15278. __extends(PointerInfo, _super);
  15279. function PointerInfo(type, event, pickInfo) {
  15280. var _this = _super.call(this, type, event) || this;
  15281. _this.pickInfo = pickInfo;
  15282. return _this;
  15283. }
  15284. return PointerInfo;
  15285. }(PointerInfoBase));
  15286. BABYLON.PointerInfo = PointerInfo;
  15287. /**
  15288. * This class is used by the onRenderingGroupObservable
  15289. */
  15290. var RenderingGroupInfo = (function () {
  15291. function RenderingGroupInfo() {
  15292. }
  15293. return RenderingGroupInfo;
  15294. }());
  15295. /**
  15296. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15297. * This stage will be fired no matter what
  15298. */
  15299. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15300. /**
  15301. * Called before opaque object are rendered.
  15302. * This stage will be fired only if there's 3D Opaque content to render
  15303. */
  15304. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15305. /**
  15306. * Called after the opaque objects are rendered and before the transparent ones
  15307. * This stage will be fired only if there's 3D transparent content to render
  15308. */
  15309. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15310. /**
  15311. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15312. * This stage will be fired no matter what
  15313. */
  15314. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15315. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15316. /**
  15317. * Represents a scene to be rendered by the engine.
  15318. * @see http://doc.babylonjs.com/page.php?p=21911
  15319. */
  15320. var Scene = (function () {
  15321. /**
  15322. * @constructor
  15323. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15324. */
  15325. function Scene(engine) {
  15326. // Members
  15327. this.autoClear = true;
  15328. this.autoClearDepthAndStencil = true;
  15329. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15330. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15331. this.forceWireframe = false;
  15332. this._forcePointsCloud = false;
  15333. this.forceShowBoundingBoxes = false;
  15334. this.animationsEnabled = true;
  15335. this.constantlyUpdateMeshUnderPointer = false;
  15336. this.hoverCursor = "pointer";
  15337. // Metadata
  15338. this.metadata = null;
  15339. // Events
  15340. /**
  15341. * An event triggered when the scene is disposed.
  15342. * @type {BABYLON.Observable}
  15343. */
  15344. this.onDisposeObservable = new BABYLON.Observable();
  15345. /**
  15346. * An event triggered before rendering the scene
  15347. * @type {BABYLON.Observable}
  15348. */
  15349. this.onBeforeRenderObservable = new BABYLON.Observable();
  15350. /**
  15351. * An event triggered after rendering the scene
  15352. * @type {BABYLON.Observable}
  15353. */
  15354. this.onAfterRenderObservable = new BABYLON.Observable();
  15355. /**
  15356. * An event triggered when the scene is ready
  15357. * @type {BABYLON.Observable}
  15358. */
  15359. this.onReadyObservable = new BABYLON.Observable();
  15360. /**
  15361. * An event triggered before rendering a camera
  15362. * @type {BABYLON.Observable}
  15363. */
  15364. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15365. /**
  15366. * An event triggered after rendering a camera
  15367. * @type {BABYLON.Observable}
  15368. */
  15369. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15370. /**
  15371. * An event triggered when a camera is created
  15372. * @type {BABYLON.Observable}
  15373. */
  15374. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15375. /**
  15376. * An event triggered when a camera is removed
  15377. * @type {BABYLON.Observable}
  15378. */
  15379. this.onCameraRemovedObservable = new BABYLON.Observable();
  15380. /**
  15381. * An event triggered when a light is created
  15382. * @type {BABYLON.Observable}
  15383. */
  15384. this.onNewLightAddedObservable = new BABYLON.Observable();
  15385. /**
  15386. * An event triggered when a light is removed
  15387. * @type {BABYLON.Observable}
  15388. */
  15389. this.onLightRemovedObservable = new BABYLON.Observable();
  15390. /**
  15391. * An event triggered when a geometry is created
  15392. * @type {BABYLON.Observable}
  15393. */
  15394. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15395. /**
  15396. * An event triggered when a geometry is removed
  15397. * @type {BABYLON.Observable}
  15398. */
  15399. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15400. /**
  15401. * An event triggered when a mesh is created
  15402. * @type {BABYLON.Observable}
  15403. */
  15404. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15405. /**
  15406. * An event triggered when a mesh is removed
  15407. * @type {BABYLON.Observable}
  15408. */
  15409. this.onMeshRemovedObservable = new BABYLON.Observable();
  15410. /**
  15411. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15412. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15413. * 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)
  15414. */
  15415. this.onRenderingGroupObservable = new BABYLON.Observable();
  15416. // Animations
  15417. this.animations = [];
  15418. /**
  15419. * 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).
  15420. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15421. */
  15422. this.onPrePointerObservable = new BABYLON.Observable();
  15423. /**
  15424. * Observable event triggered each time an input event is received from the rendering canvas
  15425. */
  15426. this.onPointerObservable = new BABYLON.Observable();
  15427. this._meshPickProceed = false;
  15428. this._previousHasSwiped = false;
  15429. this._currentPickResult = null;
  15430. this._previousPickResult = null;
  15431. this._isButtonPressed = false;
  15432. this._doubleClickOccured = false;
  15433. 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
  15434. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15435. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15436. this._startingPointerTime = 0;
  15437. this._previousStartingPointerTime = 0;
  15438. // Coordinate system
  15439. /**
  15440. * use right-handed coordinate system on this scene.
  15441. * @type {boolean}
  15442. */
  15443. this._useRightHandedSystem = false;
  15444. // Fog
  15445. /**
  15446. * is fog enabled on this scene.
  15447. * @type {boolean}
  15448. */
  15449. this._fogEnabled = true;
  15450. this._fogMode = Scene.FOGMODE_NONE;
  15451. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15452. this.fogDensity = 0.1;
  15453. this.fogStart = 0;
  15454. this.fogEnd = 1000.0;
  15455. // Lights
  15456. /**
  15457. * is shadow enabled on this scene.
  15458. * @type {boolean}
  15459. */
  15460. this._shadowsEnabled = true;
  15461. /**
  15462. * is light enabled on this scene.
  15463. * @type {boolean}
  15464. */
  15465. this._lightsEnabled = true;
  15466. /**
  15467. * All of the lights added to this scene.
  15468. * @see BABYLON.Light
  15469. * @type {BABYLON.Light[]}
  15470. */
  15471. this.lights = new Array();
  15472. // Cameras
  15473. /**
  15474. * All of the cameras added to this scene.
  15475. * @see BABYLON.Camera
  15476. * @type {BABYLON.Camera[]}
  15477. */
  15478. this.cameras = new Array();
  15479. this.activeCameras = new Array();
  15480. // Meshes
  15481. /**
  15482. * All of the (abstract) meshes added to this scene.
  15483. * @see BABYLON.AbstractMesh
  15484. * @type {BABYLON.AbstractMesh[]}
  15485. */
  15486. this.meshes = new Array();
  15487. // Geometries
  15488. this._geometries = new Array();
  15489. this.materials = new Array();
  15490. this.multiMaterials = new Array();
  15491. // Textures
  15492. this._texturesEnabled = true;
  15493. this.textures = new Array();
  15494. // Particles
  15495. this.particlesEnabled = true;
  15496. this.particleSystems = new Array();
  15497. // Sprites
  15498. this.spritesEnabled = true;
  15499. this.spriteManagers = new Array();
  15500. // Layers
  15501. this.layers = new Array();
  15502. this.highlightLayers = new Array();
  15503. // Skeletons
  15504. this._skeletonsEnabled = true;
  15505. this.skeletons = new Array();
  15506. // Morph targets
  15507. this.morphTargetManagers = new Array();
  15508. // Lens flares
  15509. this.lensFlaresEnabled = true;
  15510. this.lensFlareSystems = new Array();
  15511. // Collisions
  15512. this.collisionsEnabled = true;
  15513. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15514. // Postprocesses
  15515. this.postProcessesEnabled = true;
  15516. // Customs render targets
  15517. this.renderTargetsEnabled = true;
  15518. this.dumpNextRenderTargets = false;
  15519. this.customRenderTargets = new Array();
  15520. // Imported meshes
  15521. this.importedMeshesFiles = new Array();
  15522. // Probes
  15523. this.probesEnabled = true;
  15524. this.reflectionProbes = new Array();
  15525. this._actionManagers = new Array();
  15526. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15527. // Procedural textures
  15528. this.proceduralTexturesEnabled = true;
  15529. this._proceduralTextures = new Array();
  15530. this.soundTracks = new Array();
  15531. this._audioEnabled = true;
  15532. this._headphone = false;
  15533. // Performance counters
  15534. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15535. this._totalLightsCounter = new BABYLON.PerfCounter();
  15536. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15537. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15538. this._totalVertices = new BABYLON.PerfCounter();
  15539. this._activeIndices = new BABYLON.PerfCounter();
  15540. this._activeParticles = new BABYLON.PerfCounter();
  15541. this._lastFrameDuration = new BABYLON.PerfCounter();
  15542. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15543. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15544. this._particlesDuration = new BABYLON.PerfCounter();
  15545. this._renderDuration = new BABYLON.PerfCounter();
  15546. this._spritesDuration = new BABYLON.PerfCounter();
  15547. this._activeBones = new BABYLON.PerfCounter();
  15548. this._animationTime = 0;
  15549. this.animationTimeScale = 1;
  15550. this._renderId = 0;
  15551. this._executeWhenReadyTimeoutId = -1;
  15552. this._intermediateRendering = false;
  15553. this._viewUpdateFlag = -1;
  15554. this._projectionUpdateFlag = -1;
  15555. this._toBeDisposed = new BABYLON.SmartArray(256);
  15556. this._pendingData = []; //ANY
  15557. this._activeMeshes = new BABYLON.SmartArray(256);
  15558. this._processedMaterials = new BABYLON.SmartArray(256);
  15559. this._renderTargets = new BABYLON.SmartArray(256);
  15560. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15561. this._activeSkeletons = new BABYLON.SmartArray(32);
  15562. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15563. this._activeAnimatables = new Array();
  15564. this._transformMatrix = BABYLON.Matrix.Zero();
  15565. this.requireLightSorting = false;
  15566. this._uniqueIdCounter = 0;
  15567. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15568. this._engine.scenes.push(this);
  15569. this._uid = null;
  15570. this._renderingManager = new BABYLON.RenderingManager(this);
  15571. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15572. if (BABYLON.OutlineRenderer) {
  15573. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15574. }
  15575. this.attachControl();
  15576. if (BABYLON.SoundTrack) {
  15577. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15578. }
  15579. //simplification queue
  15580. if (BABYLON.SimplificationQueue) {
  15581. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15582. }
  15583. //collision coordinator initialization. For now legacy per default.
  15584. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15585. // Uniform Buffer
  15586. this._createUbo();
  15587. }
  15588. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15589. get: function () {
  15590. return Scene._FOGMODE_NONE;
  15591. },
  15592. enumerable: true,
  15593. configurable: true
  15594. });
  15595. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15596. get: function () {
  15597. return Scene._FOGMODE_EXP;
  15598. },
  15599. enumerable: true,
  15600. configurable: true
  15601. });
  15602. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15603. get: function () {
  15604. return Scene._FOGMODE_EXP2;
  15605. },
  15606. enumerable: true,
  15607. configurable: true
  15608. });
  15609. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15610. get: function () {
  15611. return Scene._FOGMODE_LINEAR;
  15612. },
  15613. enumerable: true,
  15614. configurable: true
  15615. });
  15616. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15617. /**
  15618. * Texture used in all pbr material as the reflection texture.
  15619. * As in the majority of the scene they are the same (exception for multi room and so on),
  15620. * this is easier to reference from here than from all the materials.
  15621. */
  15622. get: function () {
  15623. return this._environmentTexture;
  15624. },
  15625. /**
  15626. * Texture used in all pbr material as the reflection texture.
  15627. * As in the majority of the scene they are the same (exception for multi room and so on),
  15628. * this is easier to set here than in all the materials.
  15629. */
  15630. set: function (value) {
  15631. this._environmentTexture = value;
  15632. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15633. },
  15634. enumerable: true,
  15635. configurable: true
  15636. });
  15637. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15638. get: function () {
  15639. return this._forcePointsCloud;
  15640. },
  15641. set: function (value) {
  15642. if (this._forcePointsCloud === value) {
  15643. return;
  15644. }
  15645. this._forcePointsCloud = value;
  15646. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15647. },
  15648. enumerable: true,
  15649. configurable: true
  15650. });
  15651. Object.defineProperty(Scene.prototype, "onDispose", {
  15652. set: function (callback) {
  15653. if (this._onDisposeObserver) {
  15654. this.onDisposeObservable.remove(this._onDisposeObserver);
  15655. }
  15656. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15657. },
  15658. enumerable: true,
  15659. configurable: true
  15660. });
  15661. Object.defineProperty(Scene.prototype, "beforeRender", {
  15662. set: function (callback) {
  15663. if (this._onBeforeRenderObserver) {
  15664. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15665. }
  15666. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Scene.prototype, "afterRender", {
  15672. set: function (callback) {
  15673. if (this._onAfterRenderObserver) {
  15674. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15675. }
  15676. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15682. set: function (callback) {
  15683. if (this._onBeforeCameraRenderObserver) {
  15684. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15685. }
  15686. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15687. },
  15688. enumerable: true,
  15689. configurable: true
  15690. });
  15691. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15692. set: function (callback) {
  15693. if (this._onAfterCameraRenderObserver) {
  15694. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15695. }
  15696. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15697. },
  15698. enumerable: true,
  15699. configurable: true
  15700. });
  15701. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15702. get: function () {
  15703. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15704. },
  15705. enumerable: true,
  15706. configurable: true
  15707. });
  15708. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15709. get: function () {
  15710. return this._useRightHandedSystem;
  15711. },
  15712. set: function (value) {
  15713. if (this._useRightHandedSystem === value) {
  15714. return;
  15715. }
  15716. this._useRightHandedSystem = value;
  15717. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15718. },
  15719. enumerable: true,
  15720. configurable: true
  15721. });
  15722. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15723. get: function () {
  15724. return this._fogEnabled;
  15725. },
  15726. set: function (value) {
  15727. if (this._fogEnabled === value) {
  15728. return;
  15729. }
  15730. this._fogEnabled = value;
  15731. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15732. },
  15733. enumerable: true,
  15734. configurable: true
  15735. });
  15736. Object.defineProperty(Scene.prototype, "fogMode", {
  15737. get: function () {
  15738. return this._fogMode;
  15739. },
  15740. set: function (value) {
  15741. if (this._fogMode === value) {
  15742. return;
  15743. }
  15744. this._fogMode = value;
  15745. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15746. },
  15747. enumerable: true,
  15748. configurable: true
  15749. });
  15750. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15751. get: function () {
  15752. return this._shadowsEnabled;
  15753. },
  15754. set: function (value) {
  15755. if (this._shadowsEnabled === value) {
  15756. return;
  15757. }
  15758. this._shadowsEnabled = value;
  15759. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15765. get: function () {
  15766. return this._lightsEnabled;
  15767. },
  15768. set: function (value) {
  15769. if (this._lightsEnabled === value) {
  15770. return;
  15771. }
  15772. this._lightsEnabled = value;
  15773. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15779. get: function () {
  15780. if (!this._defaultMaterial) {
  15781. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15782. }
  15783. return this._defaultMaterial;
  15784. },
  15785. set: function (value) {
  15786. this._defaultMaterial = value;
  15787. },
  15788. enumerable: true,
  15789. configurable: true
  15790. });
  15791. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15792. get: function () {
  15793. return this._texturesEnabled;
  15794. },
  15795. set: function (value) {
  15796. if (this._texturesEnabled === value) {
  15797. return;
  15798. }
  15799. this._texturesEnabled = value;
  15800. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15801. },
  15802. enumerable: true,
  15803. configurable: true
  15804. });
  15805. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15806. get: function () {
  15807. return this._skeletonsEnabled;
  15808. },
  15809. set: function (value) {
  15810. if (this._skeletonsEnabled === value) {
  15811. return;
  15812. }
  15813. this._skeletonsEnabled = value;
  15814. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15815. },
  15816. enumerable: true,
  15817. configurable: true
  15818. });
  15819. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15820. get: function () {
  15821. if (!this._postProcessRenderPipelineManager) {
  15822. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15823. }
  15824. return this._postProcessRenderPipelineManager;
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15830. get: function () {
  15831. return this._frustumPlanes;
  15832. },
  15833. enumerable: true,
  15834. configurable: true
  15835. });
  15836. Object.defineProperty(Scene.prototype, "debugLayer", {
  15837. // Properties
  15838. get: function () {
  15839. if (!this._debugLayer) {
  15840. this._debugLayer = new BABYLON.DebugLayer(this);
  15841. }
  15842. return this._debugLayer;
  15843. },
  15844. enumerable: true,
  15845. configurable: true
  15846. });
  15847. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15848. get: function () {
  15849. return this._workerCollisions;
  15850. },
  15851. set: function (enabled) {
  15852. if (!BABYLON.CollisionCoordinatorLegacy) {
  15853. return;
  15854. }
  15855. enabled = (enabled && !!Worker);
  15856. this._workerCollisions = enabled;
  15857. if (this.collisionCoordinator) {
  15858. this.collisionCoordinator.destroy();
  15859. }
  15860. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15861. this.collisionCoordinator.init(this);
  15862. },
  15863. enumerable: true,
  15864. configurable: true
  15865. });
  15866. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15867. get: function () {
  15868. return this._selectionOctree;
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15874. /**
  15875. * The mesh that is currently under the pointer.
  15876. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15877. */
  15878. get: function () {
  15879. return this._pointerOverMesh;
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. Object.defineProperty(Scene.prototype, "pointerX", {
  15885. /**
  15886. * Current on-screen X position of the pointer
  15887. * @return {number} X position of the pointer
  15888. */
  15889. get: function () {
  15890. return this._pointerX;
  15891. },
  15892. enumerable: true,
  15893. configurable: true
  15894. });
  15895. Object.defineProperty(Scene.prototype, "pointerY", {
  15896. /**
  15897. * Current on-screen Y position of the pointer
  15898. * @return {number} Y position of the pointer
  15899. */
  15900. get: function () {
  15901. return this._pointerY;
  15902. },
  15903. enumerable: true,
  15904. configurable: true
  15905. });
  15906. Scene.prototype.getCachedMaterial = function () {
  15907. return this._cachedMaterial;
  15908. };
  15909. Scene.prototype.getCachedEffect = function () {
  15910. return this._cachedEffect;
  15911. };
  15912. Scene.prototype.getCachedVisibility = function () {
  15913. return this._cachedVisibility;
  15914. };
  15915. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15916. if (visibility === void 0) { visibility = 0; }
  15917. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15918. };
  15919. Scene.prototype.getBoundingBoxRenderer = function () {
  15920. if (!this._boundingBoxRenderer) {
  15921. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15922. }
  15923. return this._boundingBoxRenderer;
  15924. };
  15925. Scene.prototype.getOutlineRenderer = function () {
  15926. return this._outlineRenderer;
  15927. };
  15928. Scene.prototype.getEngine = function () {
  15929. return this._engine;
  15930. };
  15931. Scene.prototype.getTotalVertices = function () {
  15932. return this._totalVertices.current;
  15933. };
  15934. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15935. get: function () {
  15936. return this._totalVertices;
  15937. },
  15938. enumerable: true,
  15939. configurable: true
  15940. });
  15941. Scene.prototype.getActiveIndices = function () {
  15942. return this._activeIndices.current;
  15943. };
  15944. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15945. get: function () {
  15946. return this._activeIndices;
  15947. },
  15948. enumerable: true,
  15949. configurable: true
  15950. });
  15951. Scene.prototype.getActiveParticles = function () {
  15952. return this._activeParticles.current;
  15953. };
  15954. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15955. get: function () {
  15956. return this._activeParticles;
  15957. },
  15958. enumerable: true,
  15959. configurable: true
  15960. });
  15961. Scene.prototype.getActiveBones = function () {
  15962. return this._activeBones.current;
  15963. };
  15964. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15965. get: function () {
  15966. return this._activeBones;
  15967. },
  15968. enumerable: true,
  15969. configurable: true
  15970. });
  15971. // Stats
  15972. Scene.prototype.getLastFrameDuration = function () {
  15973. return this._lastFrameDuration.current;
  15974. };
  15975. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15976. get: function () {
  15977. return this._lastFrameDuration;
  15978. },
  15979. enumerable: true,
  15980. configurable: true
  15981. });
  15982. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15983. return this._evaluateActiveMeshesDuration.current;
  15984. };
  15985. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15986. get: function () {
  15987. return this._evaluateActiveMeshesDuration;
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Scene.prototype.getActiveMeshes = function () {
  15993. return this._activeMeshes;
  15994. };
  15995. Scene.prototype.getRenderTargetsDuration = function () {
  15996. return this._renderTargetsDuration.current;
  15997. };
  15998. Scene.prototype.getRenderDuration = function () {
  15999. return this._renderDuration.current;
  16000. };
  16001. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16002. get: function () {
  16003. return this._renderDuration;
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Scene.prototype.getParticlesDuration = function () {
  16009. return this._particlesDuration.current;
  16010. };
  16011. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16012. get: function () {
  16013. return this._particlesDuration;
  16014. },
  16015. enumerable: true,
  16016. configurable: true
  16017. });
  16018. Scene.prototype.getSpritesDuration = function () {
  16019. return this._spritesDuration.current;
  16020. };
  16021. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16022. get: function () {
  16023. return this._spritesDuration;
  16024. },
  16025. enumerable: true,
  16026. configurable: true
  16027. });
  16028. Scene.prototype.getAnimationRatio = function () {
  16029. return this._animationRatio;
  16030. };
  16031. Scene.prototype.getRenderId = function () {
  16032. return this._renderId;
  16033. };
  16034. Scene.prototype.incrementRenderId = function () {
  16035. this._renderId++;
  16036. };
  16037. Scene.prototype._updatePointerPosition = function (evt) {
  16038. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16039. this._pointerX = evt.clientX - canvasRect.left;
  16040. this._pointerY = evt.clientY - canvasRect.top;
  16041. this._unTranslatedPointerX = this._pointerX;
  16042. this._unTranslatedPointerY = this._pointerY;
  16043. if (this.cameraToUseForPointers) {
  16044. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16045. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16046. }
  16047. };
  16048. Scene.prototype._createUbo = function () {
  16049. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16050. this._sceneUbo.addUniform("viewProjection", 16);
  16051. this._sceneUbo.addUniform("view", 16);
  16052. };
  16053. // Pointers handling
  16054. /**
  16055. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16056. * @param attachUp defines if you want to attach events to pointerup
  16057. * @param attachDown defines if you want to attach events to pointerdown
  16058. * @param attachMove defines if you want to attach events to pointermove
  16059. */
  16060. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16061. var _this = this;
  16062. if (attachUp === void 0) { attachUp = true; }
  16063. if (attachDown === void 0) { attachDown = true; }
  16064. if (attachMove === void 0) { attachMove = true; }
  16065. this._initActionManager = function (act, clickInfo) {
  16066. if (!_this._meshPickProceed) {
  16067. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16068. _this._currentPickResult = pickResult;
  16069. if (pickResult) {
  16070. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16071. }
  16072. _this._meshPickProceed = true;
  16073. }
  16074. return act;
  16075. };
  16076. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16077. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16078. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16079. btn !== _this._previousButtonPressed) {
  16080. _this._doubleClickOccured = false;
  16081. clickInfo.singleClick = true;
  16082. clickInfo.ignore = false;
  16083. cb(clickInfo, _this._currentPickResult);
  16084. }
  16085. };
  16086. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16087. var clickInfo = new ClickInfo();
  16088. _this._currentPickResult = null;
  16089. var act;
  16090. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16091. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16092. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16093. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16094. act = _this._initActionManager(act, clickInfo);
  16095. if (act)
  16096. checkPicking = act.hasPickTriggers;
  16097. }
  16098. if (checkPicking) {
  16099. var btn = evt.button;
  16100. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16101. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16102. if (!clickInfo.hasSwiped) {
  16103. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16104. if (!checkSingleClickImmediately) {
  16105. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16106. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16107. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16108. act = _this._initActionManager(act, clickInfo);
  16109. if (act)
  16110. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16111. }
  16112. }
  16113. if (checkSingleClickImmediately) {
  16114. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16115. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16116. btn !== _this._previousButtonPressed) {
  16117. clickInfo.singleClick = true;
  16118. cb(clickInfo, _this._currentPickResult);
  16119. }
  16120. }
  16121. else {
  16122. // wait that no double click has been raised during the double click delay
  16123. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16124. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16125. }
  16126. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16127. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16128. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16129. act = _this._initActionManager(act, clickInfo);
  16130. if (act)
  16131. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16132. }
  16133. if (checkDoubleClick) {
  16134. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16135. if (btn === _this._previousButtonPressed &&
  16136. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16137. !_this._doubleClickOccured) {
  16138. // pointer has not moved for 2 clicks, it's a double click
  16139. if (!clickInfo.hasSwiped &&
  16140. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16141. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16142. _this._previousStartingPointerTime = 0;
  16143. _this._doubleClickOccured = true;
  16144. clickInfo.doubleClick = true;
  16145. clickInfo.ignore = false;
  16146. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16147. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16148. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16149. cb(clickInfo, _this._currentPickResult);
  16150. }
  16151. else {
  16152. _this._doubleClickOccured = false;
  16153. _this._previousStartingPointerTime = _this._startingPointerTime;
  16154. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16155. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16156. _this._previousButtonPressed = btn;
  16157. _this._previousHasSwiped = clickInfo.hasSwiped;
  16158. if (Scene.ExclusiveDoubleClickMode) {
  16159. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16160. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16161. }
  16162. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16163. cb(clickInfo, _this._previousPickResult);
  16164. }
  16165. else {
  16166. cb(clickInfo, _this._currentPickResult);
  16167. }
  16168. }
  16169. }
  16170. else {
  16171. _this._doubleClickOccured = false;
  16172. _this._previousStartingPointerTime = _this._startingPointerTime;
  16173. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16174. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16175. _this._previousButtonPressed = btn;
  16176. _this._previousHasSwiped = clickInfo.hasSwiped;
  16177. }
  16178. }
  16179. }
  16180. }
  16181. clickInfo.ignore = true;
  16182. cb(clickInfo, _this._currentPickResult);
  16183. };
  16184. var spritePredicate = function (sprite) {
  16185. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16186. };
  16187. this._onPointerMove = function (evt) {
  16188. _this._updatePointerPosition(evt);
  16189. // PreObservable support
  16190. if (_this.onPrePointerObservable.hasObservers()) {
  16191. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16192. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16193. _this.onPrePointerObservable.notifyObservers(pi, type);
  16194. if (pi.skipOnPointerObservable) {
  16195. return;
  16196. }
  16197. }
  16198. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16199. return;
  16200. }
  16201. var canvas = _this._engine.getRenderingCanvas();
  16202. if (!_this.pointerMovePredicate) {
  16203. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16204. }
  16205. // Meshes
  16206. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16207. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16208. _this.setPointerOverSprite(null);
  16209. _this.setPointerOverMesh(pickResult.pickedMesh);
  16210. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16211. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16212. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16213. }
  16214. else {
  16215. canvas.style.cursor = _this.hoverCursor;
  16216. }
  16217. }
  16218. else {
  16219. canvas.style.cursor = "";
  16220. }
  16221. }
  16222. else {
  16223. _this.setPointerOverMesh(null);
  16224. // Sprites
  16225. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16226. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16227. _this.setPointerOverSprite(pickResult.pickedSprite);
  16228. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16229. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16230. }
  16231. else {
  16232. canvas.style.cursor = _this.hoverCursor;
  16233. }
  16234. }
  16235. else {
  16236. _this.setPointerOverSprite(null);
  16237. // Restore pointer
  16238. canvas.style.cursor = "";
  16239. }
  16240. }
  16241. if (_this.onPointerMove) {
  16242. _this.onPointerMove(evt, pickResult);
  16243. }
  16244. if (_this.onPointerObservable.hasObservers()) {
  16245. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16246. var pi = new PointerInfo(type, evt, pickResult);
  16247. _this.onPointerObservable.notifyObservers(pi, type);
  16248. }
  16249. };
  16250. this._onPointerDown = function (evt) {
  16251. _this._isButtonPressed = true;
  16252. _this._pickedDownMesh = null;
  16253. _this._meshPickProceed = false;
  16254. _this._updatePointerPosition(evt);
  16255. // PreObservable support
  16256. if (_this.onPrePointerObservable.hasObservers()) {
  16257. var type = PointerEventTypes.POINTERDOWN;
  16258. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16259. _this.onPrePointerObservable.notifyObservers(pi, type);
  16260. if (pi.skipOnPointerObservable) {
  16261. return;
  16262. }
  16263. }
  16264. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16265. return;
  16266. }
  16267. _this._startingPointerPosition.x = _this._pointerX;
  16268. _this._startingPointerPosition.y = _this._pointerY;
  16269. _this._startingPointerTime = new Date().getTime();
  16270. if (!_this.pointerDownPredicate) {
  16271. _this.pointerDownPredicate = function (mesh) {
  16272. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16273. };
  16274. }
  16275. // Meshes
  16276. _this._pickedDownMesh = null;
  16277. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16278. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16279. _this._pickedDownMesh = pickResult.pickedMesh;
  16280. var actionManager = pickResult.pickedMesh.actionManager;
  16281. if (actionManager) {
  16282. if (actionManager.hasPickTriggers) {
  16283. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16284. switch (evt.button) {
  16285. case 0:
  16286. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16287. break;
  16288. case 1:
  16289. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16290. break;
  16291. case 2:
  16292. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16293. break;
  16294. }
  16295. }
  16296. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16297. window.setTimeout((function () {
  16298. var _this = this;
  16299. 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);
  16300. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16301. if (this._isButtonPressed &&
  16302. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16303. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16304. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16305. this._startingPointerTime = 0;
  16306. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16307. }
  16308. }
  16309. }).bind(_this), Scene.LongPressDelay);
  16310. }
  16311. }
  16312. }
  16313. if (_this.onPointerDown) {
  16314. _this.onPointerDown(evt, pickResult);
  16315. }
  16316. if (_this.onPointerObservable.hasObservers()) {
  16317. var type = PointerEventTypes.POINTERDOWN;
  16318. var pi = new PointerInfo(type, evt, pickResult);
  16319. _this.onPointerObservable.notifyObservers(pi, type);
  16320. }
  16321. // Sprites
  16322. _this._pickedDownSprite = null;
  16323. if (_this.spriteManagers.length > 0) {
  16324. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16325. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16326. if (pickResult.pickedSprite.actionManager) {
  16327. _this._pickedDownSprite = pickResult.pickedSprite;
  16328. switch (evt.button) {
  16329. case 0:
  16330. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16331. break;
  16332. case 1:
  16333. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16334. break;
  16335. case 2:
  16336. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16337. break;
  16338. }
  16339. if (pickResult.pickedSprite.actionManager) {
  16340. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16341. }
  16342. }
  16343. }
  16344. }
  16345. };
  16346. this._onPointerUp = function (evt) {
  16347. _this._isButtonPressed = false;
  16348. _this._pickedUpMesh = null;
  16349. _this._meshPickProceed = false;
  16350. _this._updatePointerPosition(evt);
  16351. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16352. // PreObservable support
  16353. if (this.onPrePointerObservable.hasObservers()) {
  16354. if (!clickInfo.ignore) {
  16355. if (!clickInfo.hasSwiped) {
  16356. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16357. var type = PointerEventTypes.POINTERTAP;
  16358. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16359. this.onPrePointerObservable.notifyObservers(pi, type);
  16360. if (pi.skipOnPointerObservable) {
  16361. return;
  16362. }
  16363. }
  16364. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16365. var type = PointerEventTypes.POINTERDOUBLETAP;
  16366. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16367. this.onPrePointerObservable.notifyObservers(pi, type);
  16368. if (pi.skipOnPointerObservable) {
  16369. return;
  16370. }
  16371. }
  16372. }
  16373. }
  16374. else {
  16375. var type = PointerEventTypes.POINTERUP;
  16376. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16377. this.onPrePointerObservable.notifyObservers(pi, type);
  16378. if (pi.skipOnPointerObservable) {
  16379. return;
  16380. }
  16381. }
  16382. }
  16383. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16384. return;
  16385. }
  16386. if (!this.pointerUpPredicate) {
  16387. this.pointerUpPredicate = function (mesh) {
  16388. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16389. };
  16390. }
  16391. // Meshes
  16392. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16393. this._initActionManager(null, clickInfo);
  16394. }
  16395. if (!pickResult) {
  16396. pickResult = this._currentPickResult;
  16397. }
  16398. if (pickResult && pickResult && pickResult.pickedMesh) {
  16399. this._pickedUpMesh = pickResult.pickedMesh;
  16400. if (this._pickedDownMesh === this._pickedUpMesh) {
  16401. if (this.onPointerPick) {
  16402. this.onPointerPick(evt, pickResult);
  16403. }
  16404. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16405. var type = PointerEventTypes.POINTERPICK;
  16406. var pi = new PointerInfo(type, evt, pickResult);
  16407. this.onPointerObservable.notifyObservers(pi, type);
  16408. }
  16409. }
  16410. if (pickResult.pickedMesh.actionManager) {
  16411. if (clickInfo.ignore) {
  16412. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16413. }
  16414. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16415. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16416. }
  16417. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16418. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16419. }
  16420. }
  16421. }
  16422. if (this._pickedDownMesh &&
  16423. this._pickedDownMesh.actionManager &&
  16424. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16425. this._pickedDownMesh !== this._pickedUpMesh) {
  16426. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16427. }
  16428. if (this.onPointerUp) {
  16429. this.onPointerUp(evt, pickResult);
  16430. }
  16431. if (this.onPointerObservable.hasObservers()) {
  16432. if (!clickInfo.ignore) {
  16433. if (!clickInfo.hasSwiped) {
  16434. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16435. var type = PointerEventTypes.POINTERTAP;
  16436. var pi = new PointerInfo(type, evt, pickResult);
  16437. this.onPointerObservable.notifyObservers(pi, type);
  16438. }
  16439. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16440. var type = PointerEventTypes.POINTERDOUBLETAP;
  16441. var pi = new PointerInfo(type, evt, pickResult);
  16442. this.onPointerObservable.notifyObservers(pi, type);
  16443. }
  16444. }
  16445. }
  16446. else {
  16447. var type = PointerEventTypes.POINTERUP;
  16448. var pi = new PointerInfo(type, evt, pickResult);
  16449. this.onPointerObservable.notifyObservers(pi, type);
  16450. }
  16451. }
  16452. // Sprites
  16453. if (this.spriteManagers.length > 0) {
  16454. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16455. if (pickResult.hit && pickResult.pickedSprite) {
  16456. if (pickResult.pickedSprite.actionManager) {
  16457. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16458. if (pickResult.pickedSprite.actionManager) {
  16459. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16460. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16461. }
  16462. }
  16463. }
  16464. }
  16465. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16466. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16467. }
  16468. }
  16469. this._previousPickResult = this._currentPickResult;
  16470. }).bind(_this));
  16471. };
  16472. this._onKeyDown = function (evt) {
  16473. if (_this.actionManager) {
  16474. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16475. }
  16476. };
  16477. this._onKeyUp = function (evt) {
  16478. if (_this.actionManager) {
  16479. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16480. }
  16481. };
  16482. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16483. var canvas = this._engine.getRenderingCanvas();
  16484. if (attachMove) {
  16485. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16486. // Wheel
  16487. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16488. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16489. }
  16490. if (attachDown) {
  16491. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16492. }
  16493. if (attachUp) {
  16494. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16495. }
  16496. canvas.tabIndex = 1;
  16497. canvas.addEventListener("keydown", this._onKeyDown, false);
  16498. canvas.addEventListener("keyup", this._onKeyUp, false);
  16499. };
  16500. Scene.prototype.detachControl = function () {
  16501. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16502. var canvas = this._engine.getRenderingCanvas();
  16503. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16504. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16505. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16506. // Wheel
  16507. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16508. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16509. canvas.removeEventListener("keydown", this._onKeyDown);
  16510. canvas.removeEventListener("keyup", this._onKeyUp);
  16511. };
  16512. // Ready
  16513. Scene.prototype.isReady = function () {
  16514. if (this._pendingData.length > 0) {
  16515. return false;
  16516. }
  16517. var index;
  16518. // Geometries
  16519. for (index = 0; index < this._geometries.length; index++) {
  16520. var geometry = this._geometries[index];
  16521. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16522. return false;
  16523. }
  16524. }
  16525. // Meshes
  16526. for (index = 0; index < this.meshes.length; index++) {
  16527. var mesh = this.meshes[index];
  16528. if (!mesh.isEnabled()) {
  16529. continue;
  16530. }
  16531. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16532. continue;
  16533. }
  16534. if (!mesh.isReady()) {
  16535. return false;
  16536. }
  16537. var mat = mesh.material;
  16538. if (mat) {
  16539. if (!mat.isReady(mesh)) {
  16540. return false;
  16541. }
  16542. }
  16543. }
  16544. return true;
  16545. };
  16546. Scene.prototype.resetCachedMaterial = function () {
  16547. this._cachedMaterial = null;
  16548. this._cachedEffect = null;
  16549. this._cachedVisibility = null;
  16550. };
  16551. Scene.prototype.registerBeforeRender = function (func) {
  16552. this.onBeforeRenderObservable.add(func);
  16553. };
  16554. Scene.prototype.unregisterBeforeRender = function (func) {
  16555. this.onBeforeRenderObservable.removeCallback(func);
  16556. };
  16557. Scene.prototype.registerAfterRender = function (func) {
  16558. this.onAfterRenderObservable.add(func);
  16559. };
  16560. Scene.prototype.unregisterAfterRender = function (func) {
  16561. this.onAfterRenderObservable.removeCallback(func);
  16562. };
  16563. Scene.prototype._addPendingData = function (data) {
  16564. this._pendingData.push(data);
  16565. };
  16566. Scene.prototype._removePendingData = function (data) {
  16567. var index = this._pendingData.indexOf(data);
  16568. if (index !== -1) {
  16569. this._pendingData.splice(index, 1);
  16570. }
  16571. };
  16572. Scene.prototype.getWaitingItemsCount = function () {
  16573. return this._pendingData.length;
  16574. };
  16575. /**
  16576. * Registers a function to be executed when the scene is ready.
  16577. * @param {Function} func - the function to be executed.
  16578. */
  16579. Scene.prototype.executeWhenReady = function (func) {
  16580. var _this = this;
  16581. this.onReadyObservable.add(func);
  16582. if (this._executeWhenReadyTimeoutId !== -1) {
  16583. return;
  16584. }
  16585. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16586. _this._checkIsReady();
  16587. }, 150);
  16588. };
  16589. Scene.prototype._checkIsReady = function () {
  16590. var _this = this;
  16591. if (this.isReady()) {
  16592. this.onReadyObservable.notifyObservers(this);
  16593. this.onReadyObservable.clear();
  16594. this._executeWhenReadyTimeoutId = -1;
  16595. return;
  16596. }
  16597. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16598. _this._checkIsReady();
  16599. }, 150);
  16600. };
  16601. // Animations
  16602. /**
  16603. * Will start the animation sequence of a given target
  16604. * @param target - the target
  16605. * @param {number} from - from which frame should animation start
  16606. * @param {number} to - till which frame should animation run.
  16607. * @param {boolean} [loop] - should the animation loop
  16608. * @param {number} [speedRatio] - the speed in which to run the animation
  16609. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16610. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16611. * @return {BABYLON.Animatable} the animatable object created for this animation
  16612. * @see BABYLON.Animatable
  16613. * @see http://doc.babylonjs.com/page.php?p=22081
  16614. */
  16615. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16616. if (speedRatio === void 0) { speedRatio = 1.0; }
  16617. if (from > to && speedRatio > 0) {
  16618. speedRatio *= -1;
  16619. }
  16620. this.stopAnimation(target);
  16621. if (!animatable) {
  16622. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16623. }
  16624. // Local animations
  16625. if (target.animations) {
  16626. animatable.appendAnimations(target, target.animations);
  16627. }
  16628. // Children animations
  16629. if (target.getAnimatables) {
  16630. var animatables = target.getAnimatables();
  16631. for (var index = 0; index < animatables.length; index++) {
  16632. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16633. }
  16634. }
  16635. animatable.reset();
  16636. return animatable;
  16637. };
  16638. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16639. if (speedRatio === undefined) {
  16640. speedRatio = 1.0;
  16641. }
  16642. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16643. return animatable;
  16644. };
  16645. Scene.prototype.getAnimatableByTarget = function (target) {
  16646. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16647. if (this._activeAnimatables[index].target === target) {
  16648. return this._activeAnimatables[index];
  16649. }
  16650. }
  16651. return null;
  16652. };
  16653. Object.defineProperty(Scene.prototype, "Animatables", {
  16654. get: function () {
  16655. return this._activeAnimatables;
  16656. },
  16657. enumerable: true,
  16658. configurable: true
  16659. });
  16660. /**
  16661. * Will stop the animation of the given target
  16662. * @param target - the target
  16663. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16664. * @see beginAnimation
  16665. */
  16666. Scene.prototype.stopAnimation = function (target, animationName) {
  16667. var animatable = this.getAnimatableByTarget(target);
  16668. if (animatable) {
  16669. animatable.stop(animationName);
  16670. }
  16671. };
  16672. Scene.prototype._animate = function () {
  16673. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16674. return;
  16675. }
  16676. // Getting time
  16677. var now = BABYLON.Tools.Now;
  16678. if (!this._animationTimeLast) {
  16679. if (this._pendingData.length > 0) {
  16680. return;
  16681. }
  16682. this._animationTimeLast = now;
  16683. }
  16684. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16685. this._animationTime += deltaTime;
  16686. this._animationTimeLast = now;
  16687. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16688. this._activeAnimatables[index]._animate(this._animationTime);
  16689. }
  16690. };
  16691. // Matrix
  16692. Scene.prototype.getViewMatrix = function () {
  16693. return this._viewMatrix;
  16694. };
  16695. Scene.prototype.getProjectionMatrix = function () {
  16696. return this._projectionMatrix;
  16697. };
  16698. Scene.prototype.getTransformMatrix = function () {
  16699. return this._transformMatrix;
  16700. };
  16701. Scene.prototype.setTransformMatrix = function (view, projection) {
  16702. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16703. return;
  16704. }
  16705. this._viewUpdateFlag = view.updateFlag;
  16706. this._projectionUpdateFlag = projection.updateFlag;
  16707. this._viewMatrix = view;
  16708. this._projectionMatrix = projection;
  16709. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16710. // Update frustum
  16711. if (!this._frustumPlanes) {
  16712. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16713. }
  16714. else {
  16715. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16716. }
  16717. if (this._sceneUbo.useUbo) {
  16718. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16719. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16720. this._sceneUbo.update();
  16721. }
  16722. };
  16723. Scene.prototype.getSceneUniformBuffer = function () {
  16724. return this._sceneUbo;
  16725. };
  16726. // Methods
  16727. Scene.prototype.getUniqueId = function () {
  16728. var result = this._uniqueIdCounter;
  16729. this._uniqueIdCounter++;
  16730. return result;
  16731. };
  16732. Scene.prototype.addMesh = function (newMesh) {
  16733. newMesh.uniqueId = this.getUniqueId();
  16734. var position = this.meshes.push(newMesh);
  16735. //notify the collision coordinator
  16736. if (this.collisionCoordinator) {
  16737. this.collisionCoordinator.onMeshAdded(newMesh);
  16738. }
  16739. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16740. };
  16741. Scene.prototype.removeMesh = function (toRemove) {
  16742. var index = this.meshes.indexOf(toRemove);
  16743. if (index !== -1) {
  16744. // Remove from the scene if mesh found
  16745. this.meshes.splice(index, 1);
  16746. }
  16747. //notify the collision coordinator
  16748. if (this.collisionCoordinator) {
  16749. this.collisionCoordinator.onMeshRemoved(toRemove);
  16750. }
  16751. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16752. return index;
  16753. };
  16754. Scene.prototype.removeSkeleton = function (toRemove) {
  16755. var index = this.skeletons.indexOf(toRemove);
  16756. if (index !== -1) {
  16757. // Remove from the scene if found
  16758. this.skeletons.splice(index, 1);
  16759. }
  16760. return index;
  16761. };
  16762. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16763. var index = this.morphTargetManagers.indexOf(toRemove);
  16764. if (index !== -1) {
  16765. // Remove from the scene if found
  16766. this.morphTargetManagers.splice(index, 1);
  16767. }
  16768. return index;
  16769. };
  16770. Scene.prototype.removeLight = function (toRemove) {
  16771. var index = this.lights.indexOf(toRemove);
  16772. if (index !== -1) {
  16773. // Remove from the scene if mesh found
  16774. this.lights.splice(index, 1);
  16775. this.sortLightsByPriority();
  16776. }
  16777. this.onLightRemovedObservable.notifyObservers(toRemove);
  16778. return index;
  16779. };
  16780. Scene.prototype.removeCamera = function (toRemove) {
  16781. var index = this.cameras.indexOf(toRemove);
  16782. if (index !== -1) {
  16783. // Remove from the scene if mesh found
  16784. this.cameras.splice(index, 1);
  16785. }
  16786. // Remove from activeCameras
  16787. var index2 = this.activeCameras.indexOf(toRemove);
  16788. if (index2 !== -1) {
  16789. // Remove from the scene if mesh found
  16790. this.activeCameras.splice(index2, 1);
  16791. }
  16792. // Reset the activeCamera
  16793. if (this.activeCamera === toRemove) {
  16794. if (this.cameras.length > 0) {
  16795. this.activeCamera = this.cameras[0];
  16796. }
  16797. else {
  16798. this.activeCamera = null;
  16799. }
  16800. }
  16801. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16802. return index;
  16803. };
  16804. Scene.prototype.addLight = function (newLight) {
  16805. newLight.uniqueId = this.getUniqueId();
  16806. this.lights.push(newLight);
  16807. this.sortLightsByPriority();
  16808. this.onNewLightAddedObservable.notifyObservers(newLight);
  16809. };
  16810. Scene.prototype.sortLightsByPriority = function () {
  16811. if (this.requireLightSorting) {
  16812. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16813. }
  16814. };
  16815. Scene.prototype.addCamera = function (newCamera) {
  16816. newCamera.uniqueId = this.getUniqueId();
  16817. var position = this.cameras.push(newCamera);
  16818. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16819. };
  16820. /**
  16821. * Switch active camera
  16822. * @param {Camera} newCamera - new active camera
  16823. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16824. */
  16825. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16826. if (attachControl === void 0) { attachControl = true; }
  16827. var canvas = this._engine.getRenderingCanvas();
  16828. this.activeCamera.detachControl(canvas);
  16829. this.activeCamera = newCamera;
  16830. if (attachControl) {
  16831. newCamera.attachControl(canvas);
  16832. }
  16833. };
  16834. /**
  16835. * sets the active camera of the scene using its ID
  16836. * @param {string} id - the camera's ID
  16837. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16838. * @see activeCamera
  16839. */
  16840. Scene.prototype.setActiveCameraByID = function (id) {
  16841. var camera = this.getCameraByID(id);
  16842. if (camera) {
  16843. this.activeCamera = camera;
  16844. return camera;
  16845. }
  16846. return null;
  16847. };
  16848. /**
  16849. * sets the active camera of the scene using its name
  16850. * @param {string} name - the camera's name
  16851. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16852. * @see activeCamera
  16853. */
  16854. Scene.prototype.setActiveCameraByName = function (name) {
  16855. var camera = this.getCameraByName(name);
  16856. if (camera) {
  16857. this.activeCamera = camera;
  16858. return camera;
  16859. }
  16860. return null;
  16861. };
  16862. /**
  16863. * get a material using its id
  16864. * @param {string} the material's ID
  16865. * @return {BABYLON.Material|null} the material or null if none found.
  16866. */
  16867. Scene.prototype.getMaterialByID = function (id) {
  16868. for (var index = 0; index < this.materials.length; index++) {
  16869. if (this.materials[index].id === id) {
  16870. return this.materials[index];
  16871. }
  16872. }
  16873. return null;
  16874. };
  16875. /**
  16876. * get a material using its name
  16877. * @param {string} the material's name
  16878. * @return {BABYLON.Material|null} the material or null if none found.
  16879. */
  16880. Scene.prototype.getMaterialByName = function (name) {
  16881. for (var index = 0; index < this.materials.length; index++) {
  16882. if (this.materials[index].name === name) {
  16883. return this.materials[index];
  16884. }
  16885. }
  16886. return null;
  16887. };
  16888. Scene.prototype.getLensFlareSystemByName = function (name) {
  16889. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16890. if (this.lensFlareSystems[index].name === name) {
  16891. return this.lensFlareSystems[index];
  16892. }
  16893. }
  16894. return null;
  16895. };
  16896. Scene.prototype.getLensFlareSystemByID = function (id) {
  16897. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16898. if (this.lensFlareSystems[index].id === id) {
  16899. return this.lensFlareSystems[index];
  16900. }
  16901. }
  16902. return null;
  16903. };
  16904. Scene.prototype.getCameraByID = function (id) {
  16905. for (var index = 0; index < this.cameras.length; index++) {
  16906. if (this.cameras[index].id === id) {
  16907. return this.cameras[index];
  16908. }
  16909. }
  16910. return null;
  16911. };
  16912. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16913. for (var index = 0; index < this.cameras.length; index++) {
  16914. if (this.cameras[index].uniqueId === uniqueId) {
  16915. return this.cameras[index];
  16916. }
  16917. }
  16918. return null;
  16919. };
  16920. /**
  16921. * get a camera using its name
  16922. * @param {string} the camera's name
  16923. * @return {BABYLON.Camera|null} the camera or null if none found.
  16924. */
  16925. Scene.prototype.getCameraByName = function (name) {
  16926. for (var index = 0; index < this.cameras.length; index++) {
  16927. if (this.cameras[index].name === name) {
  16928. return this.cameras[index];
  16929. }
  16930. }
  16931. return null;
  16932. };
  16933. /**
  16934. * get a bone using its id
  16935. * @param {string} the bone's id
  16936. * @return {BABYLON.Bone|null} the bone or null if not found
  16937. */
  16938. Scene.prototype.getBoneByID = function (id) {
  16939. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16940. var skeleton = this.skeletons[skeletonIndex];
  16941. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16942. if (skeleton.bones[boneIndex].id === id) {
  16943. return skeleton.bones[boneIndex];
  16944. }
  16945. }
  16946. }
  16947. return null;
  16948. };
  16949. /**
  16950. * get a bone using its id
  16951. * @param {string} the bone's name
  16952. * @return {BABYLON.Bone|null} the bone or null if not found
  16953. */
  16954. Scene.prototype.getBoneByName = function (name) {
  16955. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16956. var skeleton = this.skeletons[skeletonIndex];
  16957. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16958. if (skeleton.bones[boneIndex].name === name) {
  16959. return skeleton.bones[boneIndex];
  16960. }
  16961. }
  16962. }
  16963. return null;
  16964. };
  16965. /**
  16966. * get a light node using its name
  16967. * @param {string} the light's name
  16968. * @return {BABYLON.Light|null} the light or null if none found.
  16969. */
  16970. Scene.prototype.getLightByName = function (name) {
  16971. for (var index = 0; index < this.lights.length; index++) {
  16972. if (this.lights[index].name === name) {
  16973. return this.lights[index];
  16974. }
  16975. }
  16976. return null;
  16977. };
  16978. /**
  16979. * get a light node using its ID
  16980. * @param {string} the light's id
  16981. * @return {BABYLON.Light|null} the light or null if none found.
  16982. */
  16983. Scene.prototype.getLightByID = function (id) {
  16984. for (var index = 0; index < this.lights.length; index++) {
  16985. if (this.lights[index].id === id) {
  16986. return this.lights[index];
  16987. }
  16988. }
  16989. return null;
  16990. };
  16991. /**
  16992. * get a light node using its scene-generated unique ID
  16993. * @param {number} the light's unique id
  16994. * @return {BABYLON.Light|null} the light or null if none found.
  16995. */
  16996. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16997. for (var index = 0; index < this.lights.length; index++) {
  16998. if (this.lights[index].uniqueId === uniqueId) {
  16999. return this.lights[index];
  17000. }
  17001. }
  17002. return null;
  17003. };
  17004. /**
  17005. * get a particle system by id
  17006. * @param id {number} the particle system id
  17007. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17008. */
  17009. Scene.prototype.getParticleSystemByID = function (id) {
  17010. for (var index = 0; index < this.particleSystems.length; index++) {
  17011. if (this.particleSystems[index].id === id) {
  17012. return this.particleSystems[index];
  17013. }
  17014. }
  17015. return null;
  17016. };
  17017. /**
  17018. * get a geometry using its ID
  17019. * @param {string} the geometry's id
  17020. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17021. */
  17022. Scene.prototype.getGeometryByID = function (id) {
  17023. for (var index = 0; index < this._geometries.length; index++) {
  17024. if (this._geometries[index].id === id) {
  17025. return this._geometries[index];
  17026. }
  17027. }
  17028. return null;
  17029. };
  17030. /**
  17031. * add a new geometry to this scene.
  17032. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17033. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17034. * @return {boolean} was the geometry added or not
  17035. */
  17036. Scene.prototype.pushGeometry = function (geometry, force) {
  17037. if (!force && this.getGeometryByID(geometry.id)) {
  17038. return false;
  17039. }
  17040. this._geometries.push(geometry);
  17041. //notify the collision coordinator
  17042. if (this.collisionCoordinator) {
  17043. this.collisionCoordinator.onGeometryAdded(geometry);
  17044. }
  17045. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17046. return true;
  17047. };
  17048. /**
  17049. * Removes an existing geometry
  17050. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17051. * @return {boolean} was the geometry removed or not
  17052. */
  17053. Scene.prototype.removeGeometry = function (geometry) {
  17054. var index = this._geometries.indexOf(geometry);
  17055. if (index > -1) {
  17056. this._geometries.splice(index, 1);
  17057. //notify the collision coordinator
  17058. if (this.collisionCoordinator) {
  17059. this.collisionCoordinator.onGeometryDeleted(geometry);
  17060. }
  17061. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17062. return true;
  17063. }
  17064. return false;
  17065. };
  17066. Scene.prototype.getGeometries = function () {
  17067. return this._geometries;
  17068. };
  17069. /**
  17070. * Get the first added mesh found of a given ID
  17071. * @param {string} id - the id to search for
  17072. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17073. */
  17074. Scene.prototype.getMeshByID = function (id) {
  17075. for (var index = 0; index < this.meshes.length; index++) {
  17076. if (this.meshes[index].id === id) {
  17077. return this.meshes[index];
  17078. }
  17079. }
  17080. return null;
  17081. };
  17082. Scene.prototype.getMeshesByID = function (id) {
  17083. return this.meshes.filter(function (m) {
  17084. return m.id === id;
  17085. });
  17086. };
  17087. /**
  17088. * Get a mesh with its auto-generated unique id
  17089. * @param {number} uniqueId - the unique id to search for
  17090. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17091. */
  17092. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17093. for (var index = 0; index < this.meshes.length; index++) {
  17094. if (this.meshes[index].uniqueId === uniqueId) {
  17095. return this.meshes[index];
  17096. }
  17097. }
  17098. return null;
  17099. };
  17100. /**
  17101. * Get a the last added mesh found of a given ID
  17102. * @param {string} id - the id to search for
  17103. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17104. */
  17105. Scene.prototype.getLastMeshByID = function (id) {
  17106. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17107. if (this.meshes[index].id === id) {
  17108. return this.meshes[index];
  17109. }
  17110. }
  17111. return null;
  17112. };
  17113. /**
  17114. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17115. * @param {string} id - the id to search for
  17116. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17117. */
  17118. Scene.prototype.getLastEntryByID = function (id) {
  17119. var index;
  17120. for (index = this.meshes.length - 1; index >= 0; index--) {
  17121. if (this.meshes[index].id === id) {
  17122. return this.meshes[index];
  17123. }
  17124. }
  17125. for (index = this.cameras.length - 1; index >= 0; index--) {
  17126. if (this.cameras[index].id === id) {
  17127. return this.cameras[index];
  17128. }
  17129. }
  17130. for (index = this.lights.length - 1; index >= 0; index--) {
  17131. if (this.lights[index].id === id) {
  17132. return this.lights[index];
  17133. }
  17134. }
  17135. return null;
  17136. };
  17137. Scene.prototype.getNodeByID = function (id) {
  17138. var mesh = this.getMeshByID(id);
  17139. if (mesh) {
  17140. return mesh;
  17141. }
  17142. var light = this.getLightByID(id);
  17143. if (light) {
  17144. return light;
  17145. }
  17146. var camera = this.getCameraByID(id);
  17147. if (camera) {
  17148. return camera;
  17149. }
  17150. var bone = this.getBoneByID(id);
  17151. return bone;
  17152. };
  17153. Scene.prototype.getNodeByName = function (name) {
  17154. var mesh = this.getMeshByName(name);
  17155. if (mesh) {
  17156. return mesh;
  17157. }
  17158. var light = this.getLightByName(name);
  17159. if (light) {
  17160. return light;
  17161. }
  17162. var camera = this.getCameraByName(name);
  17163. if (camera) {
  17164. return camera;
  17165. }
  17166. var bone = this.getBoneByName(name);
  17167. return bone;
  17168. };
  17169. Scene.prototype.getMeshByName = function (name) {
  17170. for (var index = 0; index < this.meshes.length; index++) {
  17171. if (this.meshes[index].name === name) {
  17172. return this.meshes[index];
  17173. }
  17174. }
  17175. return null;
  17176. };
  17177. Scene.prototype.getSoundByName = function (name) {
  17178. var index;
  17179. if (BABYLON.AudioEngine) {
  17180. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17181. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17182. return this.mainSoundTrack.soundCollection[index];
  17183. }
  17184. }
  17185. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17186. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17187. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17188. return this.soundTracks[sdIndex].soundCollection[index];
  17189. }
  17190. }
  17191. }
  17192. }
  17193. return null;
  17194. };
  17195. Scene.prototype.getLastSkeletonByID = function (id) {
  17196. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17197. if (this.skeletons[index].id === id) {
  17198. return this.skeletons[index];
  17199. }
  17200. }
  17201. return null;
  17202. };
  17203. Scene.prototype.getSkeletonById = function (id) {
  17204. for (var index = 0; index < this.skeletons.length; index++) {
  17205. if (this.skeletons[index].id === id) {
  17206. return this.skeletons[index];
  17207. }
  17208. }
  17209. return null;
  17210. };
  17211. Scene.prototype.getSkeletonByName = function (name) {
  17212. for (var index = 0; index < this.skeletons.length; index++) {
  17213. if (this.skeletons[index].name === name) {
  17214. return this.skeletons[index];
  17215. }
  17216. }
  17217. return null;
  17218. };
  17219. Scene.prototype.getMorphTargetManagerById = function (id) {
  17220. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17221. if (this.morphTargetManagers[index].uniqueId === id) {
  17222. return this.morphTargetManagers[index];
  17223. }
  17224. }
  17225. return null;
  17226. };
  17227. Scene.prototype.isActiveMesh = function (mesh) {
  17228. return (this._activeMeshes.indexOf(mesh) !== -1);
  17229. };
  17230. /**
  17231. * Return a the first highlight layer of the scene with a given name.
  17232. * @param name The name of the highlight layer to look for.
  17233. * @return The highlight layer if found otherwise null.
  17234. */
  17235. Scene.prototype.getHighlightLayerByName = function (name) {
  17236. for (var index = 0; index < this.highlightLayers.length; index++) {
  17237. if (this.highlightLayers[index].name === name) {
  17238. return this.highlightLayers[index];
  17239. }
  17240. }
  17241. return null;
  17242. };
  17243. Object.defineProperty(Scene.prototype, "uid", {
  17244. /**
  17245. * Return a unique id as a string which can serve as an identifier for the scene
  17246. */
  17247. get: function () {
  17248. if (!this._uid) {
  17249. this._uid = BABYLON.Tools.RandomId();
  17250. }
  17251. return this._uid;
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. /**
  17257. * Add an externaly attached data from its key.
  17258. * This method call will fail and return false, if such key already exists.
  17259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17260. * @param key the unique key that identifies the data
  17261. * @param data the data object to associate to the key for this Engine instance
  17262. * @return true if no such key were already present and the data was added successfully, false otherwise
  17263. */
  17264. Scene.prototype.addExternalData = function (key, data) {
  17265. if (!this._externalData) {
  17266. this._externalData = new BABYLON.StringDictionary();
  17267. }
  17268. return this._externalData.add(key, data);
  17269. };
  17270. /**
  17271. * Get an externaly attached data from its key
  17272. * @param key the unique key that identifies the data
  17273. * @return the associated data, if present (can be null), or undefined if not present
  17274. */
  17275. Scene.prototype.getExternalData = function (key) {
  17276. if (!this._externalData) {
  17277. return null;
  17278. }
  17279. return this._externalData.get(key);
  17280. };
  17281. /**
  17282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17283. * @param key the unique key that identifies the data
  17284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17285. * @return the associated data, can be null if the factory returned null.
  17286. */
  17287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17288. if (!this._externalData) {
  17289. this._externalData = new BABYLON.StringDictionary();
  17290. }
  17291. return this._externalData.getOrAddWithFactory(key, factory);
  17292. };
  17293. /**
  17294. * Remove an externaly attached data from the Engine instance
  17295. * @param key the unique key that identifies the data
  17296. * @return true if the data was successfully removed, false if it doesn't exist
  17297. */
  17298. Scene.prototype.removeExternalData = function (key) {
  17299. return this._externalData.remove(key);
  17300. };
  17301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17302. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17303. var material = subMesh.getMaterial();
  17304. if (mesh.showSubMeshesBoundingBox) {
  17305. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17306. }
  17307. if (material) {
  17308. // Render targets
  17309. if (material.getRenderTargetTextures) {
  17310. if (this._processedMaterials.indexOf(material) === -1) {
  17311. this._processedMaterials.push(material);
  17312. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17313. }
  17314. }
  17315. // Dispatch
  17316. this._activeIndices.addCount(subMesh.indexCount, false);
  17317. this._renderingManager.dispatch(subMesh);
  17318. }
  17319. }
  17320. };
  17321. Scene.prototype._isInIntermediateRendering = function () {
  17322. return this._intermediateRendering;
  17323. };
  17324. Scene.prototype._evaluateActiveMeshes = function () {
  17325. this.activeCamera._activeMeshes.reset();
  17326. this._activeMeshes.reset();
  17327. this._renderingManager.reset();
  17328. this._processedMaterials.reset();
  17329. this._activeParticleSystems.reset();
  17330. this._activeSkeletons.reset();
  17331. this._softwareSkinnedMeshes.reset();
  17332. if (this._boundingBoxRenderer) {
  17333. this._boundingBoxRenderer.reset();
  17334. }
  17335. // Meshes
  17336. var meshes;
  17337. var len;
  17338. if (this._selectionOctree) {
  17339. var selection = this._selectionOctree.select(this._frustumPlanes);
  17340. meshes = selection.data;
  17341. len = selection.length;
  17342. }
  17343. else {
  17344. len = this.meshes.length;
  17345. meshes = this.meshes;
  17346. }
  17347. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17348. var mesh = meshes[meshIndex];
  17349. if (mesh.isBlocked) {
  17350. continue;
  17351. }
  17352. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17353. if (!mesh.isReady() || !mesh.isEnabled()) {
  17354. continue;
  17355. }
  17356. mesh.computeWorldMatrix();
  17357. // Intersections
  17358. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17359. this._meshesForIntersections.pushNoDuplicate(mesh);
  17360. }
  17361. // Switch to current LOD
  17362. var meshLOD = mesh.getLOD(this.activeCamera);
  17363. if (!meshLOD) {
  17364. continue;
  17365. }
  17366. mesh._preActivate();
  17367. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17368. this._activeMeshes.push(mesh);
  17369. this.activeCamera._activeMeshes.push(mesh);
  17370. mesh._activate(this._renderId);
  17371. this._activeMesh(mesh, meshLOD);
  17372. }
  17373. }
  17374. // Particle systems
  17375. this._particlesDuration.beginMonitoring();
  17376. var beforeParticlesDate = BABYLON.Tools.Now;
  17377. if (this.particlesEnabled) {
  17378. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17379. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17380. var particleSystem = this.particleSystems[particleIndex];
  17381. if (!particleSystem.isStarted()) {
  17382. continue;
  17383. }
  17384. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17385. this._activeParticleSystems.push(particleSystem);
  17386. particleSystem.animate();
  17387. this._renderingManager.dispatchParticles(particleSystem);
  17388. }
  17389. }
  17390. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17391. }
  17392. this._particlesDuration.endMonitoring(false);
  17393. };
  17394. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17395. if (mesh.skeleton && this.skeletonsEnabled) {
  17396. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17397. mesh.skeleton.prepare();
  17398. }
  17399. if (!mesh.computeBonesUsingShaders) {
  17400. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17401. }
  17402. }
  17403. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17404. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17405. }
  17406. if (mesh && mesh.subMeshes) {
  17407. // Submeshes Octrees
  17408. var len;
  17409. var subMeshes;
  17410. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17411. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17412. len = intersections.length;
  17413. subMeshes = intersections.data;
  17414. }
  17415. else {
  17416. subMeshes = mesh.subMeshes;
  17417. len = subMeshes.length;
  17418. }
  17419. for (var subIndex = 0; subIndex < len; subIndex++) {
  17420. var subMesh = subMeshes[subIndex];
  17421. this._evaluateSubMesh(subMesh, mesh);
  17422. }
  17423. }
  17424. };
  17425. Scene.prototype.updateTransformMatrix = function (force) {
  17426. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17427. };
  17428. Scene.prototype._renderForCamera = function (camera) {
  17429. var engine = this._engine;
  17430. var startTime = BABYLON.Tools.Now;
  17431. this.activeCamera = camera;
  17432. if (!this.activeCamera)
  17433. throw new Error("Active camera not set");
  17434. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17435. // Viewport
  17436. engine.setViewport(this.activeCamera.viewport);
  17437. // Camera
  17438. this.resetCachedMaterial();
  17439. this._renderId++;
  17440. this.updateTransformMatrix();
  17441. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17442. // Meshes
  17443. this._evaluateActiveMeshesDuration.beginMonitoring();
  17444. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17445. this._evaluateActiveMeshes();
  17446. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17447. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17448. // Software skinning
  17449. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17450. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17451. mesh.applySkeleton(mesh.skeleton);
  17452. }
  17453. // Render targets
  17454. this._renderTargetsDuration.beginMonitoring();
  17455. var needsRestoreFrameBuffer = false;
  17456. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17457. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17458. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17459. }
  17460. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17461. this._intermediateRendering = true;
  17462. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17463. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17464. var renderTarget = this._renderTargets.data[renderIndex];
  17465. if (renderTarget._shouldRender()) {
  17466. this._renderId++;
  17467. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17468. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17469. }
  17470. }
  17471. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17472. this._intermediateRendering = false;
  17473. this._renderId++;
  17474. needsRestoreFrameBuffer = true; // Restore back buffer
  17475. }
  17476. // Render HighlightLayer Texture
  17477. var stencilState = this._engine.getStencilBuffer();
  17478. var renderhighlights = false;
  17479. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17480. this._intermediateRendering = true;
  17481. for (var i = 0; i < this.highlightLayers.length; i++) {
  17482. var highlightLayer = this.highlightLayers[i];
  17483. if (highlightLayer.shouldRender() &&
  17484. (!highlightLayer.camera ||
  17485. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17486. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17487. renderhighlights = true;
  17488. var renderTarget = highlightLayer._mainTexture;
  17489. if (renderTarget._shouldRender()) {
  17490. this._renderId++;
  17491. renderTarget.render(false, false);
  17492. needsRestoreFrameBuffer = true;
  17493. }
  17494. }
  17495. }
  17496. this._intermediateRendering = false;
  17497. this._renderId++;
  17498. }
  17499. if (needsRestoreFrameBuffer) {
  17500. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17501. }
  17502. this._renderTargetsDuration.endMonitoring(false);
  17503. // Prepare Frame
  17504. this.postProcessManager._prepareFrame();
  17505. this._renderDuration.beginMonitoring();
  17506. // Backgrounds
  17507. var layerIndex;
  17508. var layer;
  17509. if (this.layers.length) {
  17510. engine.setDepthBuffer(false);
  17511. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17512. layer = this.layers[layerIndex];
  17513. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17514. layer.render();
  17515. }
  17516. }
  17517. engine.setDepthBuffer(true);
  17518. }
  17519. // Render
  17520. BABYLON.Tools.StartPerformanceCounter("Main render");
  17521. // Activate HighlightLayer stencil
  17522. if (renderhighlights) {
  17523. this._engine.setStencilBuffer(true);
  17524. }
  17525. this._renderingManager.render(null, null, true, true);
  17526. // Restore HighlightLayer stencil
  17527. if (renderhighlights) {
  17528. this._engine.setStencilBuffer(stencilState);
  17529. }
  17530. BABYLON.Tools.EndPerformanceCounter("Main render");
  17531. // Bounding boxes
  17532. if (this._boundingBoxRenderer) {
  17533. this._boundingBoxRenderer.render();
  17534. }
  17535. // Lens flares
  17536. if (this.lensFlaresEnabled) {
  17537. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17538. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17539. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17540. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17541. lensFlareSystem.render();
  17542. }
  17543. }
  17544. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17545. }
  17546. // Foregrounds
  17547. if (this.layers.length) {
  17548. engine.setDepthBuffer(false);
  17549. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17550. layer = this.layers[layerIndex];
  17551. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17552. layer.render();
  17553. }
  17554. }
  17555. engine.setDepthBuffer(true);
  17556. }
  17557. // Highlight Layer
  17558. if (renderhighlights) {
  17559. engine.setDepthBuffer(false);
  17560. for (var i = 0; i < this.highlightLayers.length; i++) {
  17561. if (this.highlightLayers[i].shouldRender()) {
  17562. this.highlightLayers[i].render();
  17563. }
  17564. }
  17565. engine.setDepthBuffer(true);
  17566. }
  17567. this._renderDuration.endMonitoring(false);
  17568. // Finalize frame
  17569. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17570. // Update camera
  17571. this.activeCamera._updateFromScene();
  17572. // Reset some special arrays
  17573. this._renderTargets.reset();
  17574. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17575. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17576. };
  17577. Scene.prototype._processSubCameras = function (camera) {
  17578. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17579. this._renderForCamera(camera);
  17580. return;
  17581. }
  17582. // rig cameras
  17583. for (var index = 0; index < camera._rigCameras.length; index++) {
  17584. this._renderForCamera(camera._rigCameras[index]);
  17585. }
  17586. this.activeCamera = camera;
  17587. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17588. // Update camera
  17589. this.activeCamera._updateFromScene();
  17590. };
  17591. Scene.prototype._checkIntersections = function () {
  17592. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17593. var sourceMesh = this._meshesForIntersections.data[index];
  17594. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17595. var action = sourceMesh.actionManager.actions[actionIndex];
  17596. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17597. var parameters = action.getTriggerParameter();
  17598. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17599. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17600. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17601. if (areIntersecting && currentIntersectionInProgress === -1) {
  17602. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17603. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17604. sourceMesh._intersectionsInProgress.push(otherMesh);
  17605. }
  17606. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17607. sourceMesh._intersectionsInProgress.push(otherMesh);
  17608. }
  17609. }
  17610. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17611. //They intersected, and now they don't.
  17612. //is this trigger an exit trigger? execute an event.
  17613. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17614. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17615. }
  17616. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17617. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17618. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17619. }
  17620. }
  17621. }
  17622. }
  17623. }
  17624. };
  17625. Scene.prototype.render = function () {
  17626. if (this.isDisposed) {
  17627. return;
  17628. }
  17629. this._lastFrameDuration.beginMonitoring();
  17630. this._particlesDuration.fetchNewFrame();
  17631. this._spritesDuration.fetchNewFrame();
  17632. this._activeParticles.fetchNewFrame();
  17633. this._renderDuration.fetchNewFrame();
  17634. this._renderTargetsDuration.fetchNewFrame();
  17635. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17636. this._totalVertices.fetchNewFrame();
  17637. this._activeIndices.fetchNewFrame();
  17638. this._activeBones.fetchNewFrame();
  17639. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17640. this._meshesForIntersections.reset();
  17641. this.resetCachedMaterial();
  17642. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17643. // Actions
  17644. if (this.actionManager) {
  17645. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17646. }
  17647. //Simplification Queue
  17648. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17649. this.simplificationQueue.executeNext();
  17650. }
  17651. // Animations
  17652. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17653. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17654. this._animate();
  17655. // Physics
  17656. if (this._physicsEngine) {
  17657. BABYLON.Tools.StartPerformanceCounter("Physics");
  17658. this._physicsEngine._step(deltaTime / 1000.0);
  17659. BABYLON.Tools.EndPerformanceCounter("Physics");
  17660. }
  17661. // Before render
  17662. this.onBeforeRenderObservable.notifyObservers(this);
  17663. // Customs render targets
  17664. this._renderTargetsDuration.beginMonitoring();
  17665. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17666. var engine = this.getEngine();
  17667. var currentActiveCamera = this.activeCamera;
  17668. if (this.renderTargetsEnabled) {
  17669. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17670. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17671. var renderTarget = this.customRenderTargets[customIndex];
  17672. if (renderTarget._shouldRender()) {
  17673. this._renderId++;
  17674. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17675. if (!this.activeCamera)
  17676. throw new Error("Active camera not set");
  17677. // Viewport
  17678. engine.setViewport(this.activeCamera.viewport);
  17679. // Camera
  17680. this.updateTransformMatrix();
  17681. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17682. }
  17683. }
  17684. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17685. this._renderId++;
  17686. }
  17687. // Restore back buffer
  17688. if (this.customRenderTargets.length > 0) {
  17689. engine.restoreDefaultFramebuffer();
  17690. }
  17691. this._renderTargetsDuration.endMonitoring();
  17692. this.activeCamera = currentActiveCamera;
  17693. // Procedural textures
  17694. if (this.proceduralTexturesEnabled) {
  17695. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17696. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17697. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17698. if (proceduralTexture._shouldRender()) {
  17699. proceduralTexture.render();
  17700. }
  17701. }
  17702. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17703. }
  17704. // Clear
  17705. if (this.autoClearDepthAndStencil || this.autoClear) {
  17706. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17707. }
  17708. // Shadows
  17709. if (this.shadowsEnabled) {
  17710. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17711. var light = this.lights[lightIndex];
  17712. var shadowGenerator = light.getShadowGenerator();
  17713. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17714. var shadowMap = shadowGenerator.getShadowMap();
  17715. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17716. this._renderTargets.push(shadowMap);
  17717. }
  17718. }
  17719. }
  17720. }
  17721. // Depth renderer
  17722. if (this._depthRenderer) {
  17723. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17724. }
  17725. // Geometry renderer
  17726. if (this._geometryBufferRenderer) {
  17727. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17728. }
  17729. // RenderPipeline
  17730. if (this._postProcessRenderPipelineManager) {
  17731. this._postProcessRenderPipelineManager.update();
  17732. }
  17733. // Multi-cameras?
  17734. if (this.activeCameras.length > 0) {
  17735. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17736. if (cameraIndex > 0) {
  17737. this._engine.clear(null, false, true, true);
  17738. }
  17739. this._processSubCameras(this.activeCameras[cameraIndex]);
  17740. }
  17741. }
  17742. else {
  17743. if (!this.activeCamera) {
  17744. throw new Error("No camera defined");
  17745. }
  17746. this._processSubCameras(this.activeCamera);
  17747. }
  17748. // Intersection checks
  17749. this._checkIntersections();
  17750. // Update the audio listener attached to the camera
  17751. if (BABYLON.AudioEngine) {
  17752. this._updateAudioParameters();
  17753. }
  17754. // After render
  17755. if (this.afterRender) {
  17756. this.afterRender();
  17757. }
  17758. this.onAfterRenderObservable.notifyObservers(this);
  17759. // Cleaning
  17760. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17761. this._toBeDisposed.data[index].dispose();
  17762. this._toBeDisposed[index] = null;
  17763. }
  17764. this._toBeDisposed.reset();
  17765. if (this.dumpNextRenderTargets) {
  17766. this.dumpNextRenderTargets = false;
  17767. }
  17768. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17769. this._lastFrameDuration.endMonitoring();
  17770. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17771. this._totalLightsCounter.addCount(this.lights.length, true);
  17772. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17773. this._totalTexturesCounter.addCount(this.textures.length, true);
  17774. this._activeBones.addCount(0, true);
  17775. this._activeIndices.addCount(0, true);
  17776. this._activeParticles.addCount(0, true);
  17777. };
  17778. Scene.prototype._updateAudioParameters = function () {
  17779. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17780. return;
  17781. }
  17782. var listeningCamera;
  17783. var audioEngine = BABYLON.Engine.audioEngine;
  17784. if (this.activeCameras.length > 0) {
  17785. listeningCamera = this.activeCameras[0];
  17786. }
  17787. else {
  17788. listeningCamera = this.activeCamera;
  17789. }
  17790. if (listeningCamera && audioEngine.canUseWebAudio) {
  17791. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17792. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17793. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17794. cameraDirection.normalize();
  17795. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17796. var i;
  17797. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17798. var sound = this.mainSoundTrack.soundCollection[i];
  17799. if (sound.useCustomAttenuation) {
  17800. sound.updateDistanceFromListener();
  17801. }
  17802. }
  17803. for (i = 0; i < this.soundTracks.length; i++) {
  17804. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17805. sound = this.soundTracks[i].soundCollection[j];
  17806. if (sound.useCustomAttenuation) {
  17807. sound.updateDistanceFromListener();
  17808. }
  17809. }
  17810. }
  17811. }
  17812. };
  17813. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17814. // Audio
  17815. get: function () {
  17816. return this._audioEnabled;
  17817. },
  17818. set: function (value) {
  17819. this._audioEnabled = value;
  17820. if (BABYLON.AudioEngine) {
  17821. if (this._audioEnabled) {
  17822. this._enableAudio();
  17823. }
  17824. else {
  17825. this._disableAudio();
  17826. }
  17827. }
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Scene.prototype._disableAudio = function () {
  17833. var i;
  17834. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17835. this.mainSoundTrack.soundCollection[i].pause();
  17836. }
  17837. for (i = 0; i < this.soundTracks.length; i++) {
  17838. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17839. this.soundTracks[i].soundCollection[j].pause();
  17840. }
  17841. }
  17842. };
  17843. Scene.prototype._enableAudio = function () {
  17844. var i;
  17845. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17846. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17847. this.mainSoundTrack.soundCollection[i].play();
  17848. }
  17849. }
  17850. for (i = 0; i < this.soundTracks.length; i++) {
  17851. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17852. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17853. this.soundTracks[i].soundCollection[j].play();
  17854. }
  17855. }
  17856. }
  17857. };
  17858. Object.defineProperty(Scene.prototype, "headphone", {
  17859. get: function () {
  17860. return this._headphone;
  17861. },
  17862. set: function (value) {
  17863. this._headphone = value;
  17864. if (BABYLON.AudioEngine) {
  17865. if (this._headphone) {
  17866. this._switchAudioModeForHeadphones();
  17867. }
  17868. else {
  17869. this._switchAudioModeForNormalSpeakers();
  17870. }
  17871. }
  17872. },
  17873. enumerable: true,
  17874. configurable: true
  17875. });
  17876. Scene.prototype._switchAudioModeForHeadphones = function () {
  17877. this.mainSoundTrack.switchPanningModelToHRTF();
  17878. for (var i = 0; i < this.soundTracks.length; i++) {
  17879. this.soundTracks[i].switchPanningModelToHRTF();
  17880. }
  17881. };
  17882. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17883. this.mainSoundTrack.switchPanningModelToEqualPower();
  17884. for (var i = 0; i < this.soundTracks.length; i++) {
  17885. this.soundTracks[i].switchPanningModelToEqualPower();
  17886. }
  17887. };
  17888. Scene.prototype.enableDepthRenderer = function () {
  17889. if (this._depthRenderer) {
  17890. return this._depthRenderer;
  17891. }
  17892. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17893. return this._depthRenderer;
  17894. };
  17895. Scene.prototype.disableDepthRenderer = function () {
  17896. if (!this._depthRenderer) {
  17897. return;
  17898. }
  17899. this._depthRenderer.dispose();
  17900. this._depthRenderer = null;
  17901. };
  17902. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17903. if (ratio === void 0) { ratio = 1; }
  17904. if (this._geometryBufferRenderer) {
  17905. return this._geometryBufferRenderer;
  17906. }
  17907. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17908. if (!this._geometryBufferRenderer.isSupported) {
  17909. this._geometryBufferRenderer = null;
  17910. }
  17911. return this._geometryBufferRenderer;
  17912. };
  17913. Scene.prototype.disableGeometryBufferRenderer = function () {
  17914. if (!this._geometryBufferRenderer) {
  17915. return;
  17916. }
  17917. this._geometryBufferRenderer.dispose();
  17918. this._geometryBufferRenderer = null;
  17919. };
  17920. Scene.prototype.freezeMaterials = function () {
  17921. for (var i = 0; i < this.materials.length; i++) {
  17922. this.materials[i].freeze();
  17923. }
  17924. };
  17925. Scene.prototype.unfreezeMaterials = function () {
  17926. for (var i = 0; i < this.materials.length; i++) {
  17927. this.materials[i].unfreeze();
  17928. }
  17929. };
  17930. Scene.prototype.dispose = function () {
  17931. this.beforeRender = null;
  17932. this.afterRender = null;
  17933. this.skeletons = [];
  17934. this.morphTargetManagers = [];
  17935. this.importedMeshesFiles = new Array();
  17936. if (this._depthRenderer) {
  17937. this._depthRenderer.dispose();
  17938. }
  17939. // Smart arrays
  17940. if (this.activeCamera) {
  17941. this.activeCamera._activeMeshes.dispose();
  17942. this.activeCamera = null;
  17943. }
  17944. this._activeMeshes.dispose();
  17945. this._renderingManager.dispose();
  17946. this._processedMaterials.dispose();
  17947. this._activeParticleSystems.dispose();
  17948. this._activeSkeletons.dispose();
  17949. this._softwareSkinnedMeshes.dispose();
  17950. if (this._boundingBoxRenderer) {
  17951. this._boundingBoxRenderer.dispose();
  17952. }
  17953. this._meshesForIntersections.dispose();
  17954. this._toBeDisposed.dispose();
  17955. // Debug layer
  17956. if (this._debugLayer) {
  17957. this._debugLayer.hide();
  17958. }
  17959. // Events
  17960. this.onDisposeObservable.notifyObservers(this);
  17961. this.onDisposeObservable.clear();
  17962. this.onBeforeRenderObservable.clear();
  17963. this.onAfterRenderObservable.clear();
  17964. this.detachControl();
  17965. // Release sounds & sounds tracks
  17966. if (BABYLON.AudioEngine) {
  17967. this.disposeSounds();
  17968. }
  17969. // Detach cameras
  17970. var canvas = this._engine.getRenderingCanvas();
  17971. var index;
  17972. for (index = 0; index < this.cameras.length; index++) {
  17973. this.cameras[index].detachControl(canvas);
  17974. }
  17975. // Release lights
  17976. while (this.lights.length) {
  17977. this.lights[0].dispose();
  17978. }
  17979. // Release meshes
  17980. while (this.meshes.length) {
  17981. this.meshes[0].dispose(true);
  17982. }
  17983. // Release cameras
  17984. while (this.cameras.length) {
  17985. this.cameras[0].dispose();
  17986. }
  17987. // Release materials
  17988. while (this.materials.length) {
  17989. this.materials[0].dispose();
  17990. }
  17991. // Release particles
  17992. while (this.particleSystems.length) {
  17993. this.particleSystems[0].dispose();
  17994. }
  17995. // Release sprites
  17996. while (this.spriteManagers.length) {
  17997. this.spriteManagers[0].dispose();
  17998. }
  17999. // Release layers
  18000. while (this.layers.length) {
  18001. this.layers[0].dispose();
  18002. }
  18003. while (this.highlightLayers.length) {
  18004. this.highlightLayers[0].dispose();
  18005. }
  18006. // Release textures
  18007. while (this.textures.length) {
  18008. this.textures[0].dispose();
  18009. }
  18010. // Release UBO
  18011. this._sceneUbo.dispose();
  18012. // Post-processes
  18013. this.postProcessManager.dispose();
  18014. // Physics
  18015. if (this._physicsEngine) {
  18016. this.disablePhysicsEngine();
  18017. }
  18018. // Remove from engine
  18019. index = this._engine.scenes.indexOf(this);
  18020. if (index > -1) {
  18021. this._engine.scenes.splice(index, 1);
  18022. }
  18023. this._engine.wipeCaches();
  18024. this._engine = null;
  18025. };
  18026. Object.defineProperty(Scene.prototype, "isDisposed", {
  18027. get: function () {
  18028. return !this._engine;
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. // Release sounds & sounds tracks
  18034. Scene.prototype.disposeSounds = function () {
  18035. this.mainSoundTrack.dispose();
  18036. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18037. this.soundTracks[scIndex].dispose();
  18038. }
  18039. };
  18040. // Octrees
  18041. Scene.prototype.getWorldExtends = function () {
  18042. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18043. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18044. for (var index = 0; index < this.meshes.length; index++) {
  18045. var mesh = this.meshes[index];
  18046. mesh.computeWorldMatrix(true);
  18047. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18048. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18049. BABYLON.Tools.CheckExtends(minBox, min, max);
  18050. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18051. }
  18052. return {
  18053. min: min,
  18054. max: max
  18055. };
  18056. };
  18057. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18058. if (maxCapacity === void 0) { maxCapacity = 64; }
  18059. if (maxDepth === void 0) { maxDepth = 2; }
  18060. if (!this._selectionOctree) {
  18061. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18062. }
  18063. var worldExtends = this.getWorldExtends();
  18064. // Update octree
  18065. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18066. return this._selectionOctree;
  18067. };
  18068. // Picking
  18069. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18070. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18071. var engine = this._engine;
  18072. if (!camera) {
  18073. if (!this.activeCamera)
  18074. throw new Error("Active camera not set");
  18075. camera = this.activeCamera;
  18076. }
  18077. var cameraViewport = camera.viewport;
  18078. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18079. // Moving coordinates to local viewport world
  18080. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18081. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18082. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18083. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18084. };
  18085. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18086. if (!BABYLON.PickingInfo) {
  18087. return null;
  18088. }
  18089. var engine = this._engine;
  18090. if (!camera) {
  18091. if (!this.activeCamera)
  18092. throw new Error("Active camera not set");
  18093. camera = this.activeCamera;
  18094. }
  18095. var cameraViewport = camera.viewport;
  18096. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18097. var identity = BABYLON.Matrix.Identity();
  18098. // Moving coordinates to local viewport world
  18099. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18100. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18101. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18102. };
  18103. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18104. if (!BABYLON.PickingInfo) {
  18105. return null;
  18106. }
  18107. var pickingInfo = null;
  18108. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18109. var mesh = this.meshes[meshIndex];
  18110. if (predicate) {
  18111. if (!predicate(mesh)) {
  18112. continue;
  18113. }
  18114. }
  18115. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18116. continue;
  18117. }
  18118. var world = mesh.getWorldMatrix();
  18119. var ray = rayFunction(world);
  18120. var result = mesh.intersects(ray, fastCheck);
  18121. if (!result || !result.hit)
  18122. continue;
  18123. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18124. continue;
  18125. pickingInfo = result;
  18126. if (fastCheck) {
  18127. break;
  18128. }
  18129. }
  18130. return pickingInfo || new BABYLON.PickingInfo();
  18131. };
  18132. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18133. if (!BABYLON.PickingInfo) {
  18134. return null;
  18135. }
  18136. var pickingInfos = new Array();
  18137. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18138. var mesh = this.meshes[meshIndex];
  18139. if (predicate) {
  18140. if (!predicate(mesh)) {
  18141. continue;
  18142. }
  18143. }
  18144. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18145. continue;
  18146. }
  18147. var world = mesh.getWorldMatrix();
  18148. var ray = rayFunction(world);
  18149. var result = mesh.intersects(ray, false);
  18150. if (!result || !result.hit)
  18151. continue;
  18152. pickingInfos.push(result);
  18153. }
  18154. return pickingInfos;
  18155. };
  18156. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18157. if (!BABYLON.PickingInfo) {
  18158. return null;
  18159. }
  18160. var pickingInfo = null;
  18161. camera = camera || this.activeCamera;
  18162. if (this.spriteManagers.length > 0) {
  18163. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18164. var spriteManager = this.spriteManagers[spriteIndex];
  18165. if (!spriteManager.isPickable) {
  18166. continue;
  18167. }
  18168. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18169. if (!result || !result.hit)
  18170. continue;
  18171. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18172. continue;
  18173. pickingInfo = result;
  18174. if (fastCheck) {
  18175. break;
  18176. }
  18177. }
  18178. }
  18179. return pickingInfo || new BABYLON.PickingInfo();
  18180. };
  18181. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18182. /// <param name="x">X position on screen</param>
  18183. /// <param name="y">Y position on screen</param>
  18184. /// <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>
  18185. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18186. /// <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>
  18187. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18188. var _this = this;
  18189. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18190. };
  18191. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18192. /// <param name="x">X position on screen</param>
  18193. /// <param name="y">Y position on screen</param>
  18194. /// <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>
  18195. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18196. /// <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>
  18197. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18198. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18199. };
  18200. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18201. var _this = this;
  18202. return this._internalPick(function (world) {
  18203. if (!_this._pickWithRayInverseMatrix) {
  18204. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18205. }
  18206. world.invertToRef(_this._pickWithRayInverseMatrix);
  18207. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18208. }, predicate, fastCheck);
  18209. };
  18210. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18211. /// <param name="x">X position on screen</param>
  18212. /// <param name="y">Y position on screen</param>
  18213. /// <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>
  18214. /// <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>
  18215. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18216. var _this = this;
  18217. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18218. };
  18219. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18220. /// <param name="ray">Ray to use</param>
  18221. /// <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>
  18222. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18223. var _this = this;
  18224. return this._internalMultiPick(function (world) {
  18225. if (!_this._pickWithRayInverseMatrix) {
  18226. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18227. }
  18228. world.invertToRef(_this._pickWithRayInverseMatrix);
  18229. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18230. }, predicate);
  18231. };
  18232. Scene.prototype.setPointerOverMesh = function (mesh) {
  18233. if (this._pointerOverMesh === mesh) {
  18234. return;
  18235. }
  18236. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18237. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18238. }
  18239. this._pointerOverMesh = mesh;
  18240. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18241. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18242. }
  18243. };
  18244. Scene.prototype.getPointerOverMesh = function () {
  18245. return this._pointerOverMesh;
  18246. };
  18247. Scene.prototype.setPointerOverSprite = function (sprite) {
  18248. if (this._pointerOverSprite === sprite) {
  18249. return;
  18250. }
  18251. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18252. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18253. }
  18254. this._pointerOverSprite = sprite;
  18255. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18256. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18257. }
  18258. };
  18259. Scene.prototype.getPointerOverSprite = function () {
  18260. return this._pointerOverSprite;
  18261. };
  18262. // Physics
  18263. Scene.prototype.getPhysicsEngine = function () {
  18264. return this._physicsEngine;
  18265. };
  18266. /**
  18267. * Enables physics to the current scene
  18268. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18269. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18270. * @return {boolean} was the physics engine initialized
  18271. */
  18272. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18273. if (this._physicsEngine) {
  18274. return true;
  18275. }
  18276. try {
  18277. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18278. return true;
  18279. }
  18280. catch (e) {
  18281. BABYLON.Tools.Error(e.message);
  18282. return false;
  18283. }
  18284. };
  18285. Scene.prototype.disablePhysicsEngine = function () {
  18286. if (!this._physicsEngine) {
  18287. return;
  18288. }
  18289. this._physicsEngine.dispose();
  18290. this._physicsEngine = undefined;
  18291. };
  18292. Scene.prototype.isPhysicsEnabled = function () {
  18293. return this._physicsEngine !== undefined;
  18294. };
  18295. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18296. var mesh = compound.parts[0].mesh;
  18297. mesh.physicsImpostor.dispose();
  18298. mesh.physicsImpostor = null;
  18299. };
  18300. // Misc.
  18301. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18302. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18303. // Light
  18304. if (this.lights.length === 0) {
  18305. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18306. }
  18307. // Camera
  18308. if (!this.activeCamera) {
  18309. var worldExtends = this.getWorldExtends();
  18310. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18311. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18312. var camera;
  18313. var radius = worldSize.length() * 1.5;
  18314. if (createArcRotateCamera) {
  18315. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18316. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18317. arcRotateCamera.wheelPrecision = 100 / radius;
  18318. camera = arcRotateCamera;
  18319. }
  18320. else {
  18321. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18322. freeCamera.setTarget(worldCenter);
  18323. camera = freeCamera;
  18324. }
  18325. camera.minZ = radius * 0.01;
  18326. camera.maxZ = radius * 100;
  18327. camera.speed = radius * 0.2;
  18328. this.activeCamera = camera;
  18329. }
  18330. };
  18331. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18332. if (pbr === void 0) { pbr = false; }
  18333. if (environmentTexture) {
  18334. this.environmentTexture = environmentTexture;
  18335. }
  18336. if (!this.environmentTexture) {
  18337. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18338. return;
  18339. }
  18340. if (!this.environmentTexture) {
  18341. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18342. return;
  18343. }
  18344. // Skybox
  18345. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18346. if (pbr) {
  18347. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18348. hdrSkyboxMaterial.backFaceCulling = false;
  18349. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18350. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18351. hdrSkyboxMaterial.microSurface = 1.0;
  18352. hdrSkyboxMaterial.disableLighting = true;
  18353. hdrSkybox.infiniteDistance = true;
  18354. hdrSkybox.material = hdrSkyboxMaterial;
  18355. }
  18356. else {
  18357. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18358. skyboxMaterial.backFaceCulling = false;
  18359. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18360. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18361. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18362. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18363. skyboxMaterial.disableLighting = true;
  18364. hdrSkybox.infiniteDistance = true;
  18365. hdrSkybox.material = skyboxMaterial;
  18366. }
  18367. return hdrSkybox;
  18368. };
  18369. // Tags
  18370. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18371. if (tagsQuery === undefined) {
  18372. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18373. return list;
  18374. }
  18375. var listByTags = [];
  18376. forEach = forEach || (function (item) { return; });
  18377. for (var i in list) {
  18378. var item = list[i];
  18379. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18380. listByTags.push(item);
  18381. forEach(item);
  18382. }
  18383. }
  18384. return listByTags;
  18385. };
  18386. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18387. return this._getByTags(this.meshes, tagsQuery, forEach);
  18388. };
  18389. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18390. return this._getByTags(this.cameras, tagsQuery, forEach);
  18391. };
  18392. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18393. return this._getByTags(this.lights, tagsQuery, forEach);
  18394. };
  18395. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18396. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18397. };
  18398. /**
  18399. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18400. * This allowed control for front to back rendering or reversly depending of the special needs.
  18401. *
  18402. * @param renderingGroupId The rendering group id corresponding to its index
  18403. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18404. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18405. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18406. */
  18407. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18408. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18409. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18410. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18411. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18412. };
  18413. /**
  18414. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18415. *
  18416. * @param renderingGroupId The rendering group id corresponding to its index
  18417. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18418. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18419. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18420. */
  18421. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18422. if (depth === void 0) { depth = true; }
  18423. if (stencil === void 0) { stencil = true; }
  18424. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18425. };
  18426. /**
  18427. * Will flag all materials as dirty to trigger new shader compilation
  18428. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18429. */
  18430. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18431. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18432. var material = _a[_i];
  18433. if (predicate && !predicate(material)) {
  18434. continue;
  18435. }
  18436. material.markAsDirty(flag);
  18437. }
  18438. };
  18439. return Scene;
  18440. }());
  18441. // Statics
  18442. Scene._FOGMODE_NONE = 0;
  18443. Scene._FOGMODE_EXP = 1;
  18444. Scene._FOGMODE_EXP2 = 2;
  18445. Scene._FOGMODE_LINEAR = 3;
  18446. Scene.MinDeltaTime = 1.0;
  18447. Scene.MaxDeltaTime = 1000.0;
  18448. Scene.DragMovementThreshold = 10; // in pixels
  18449. Scene.LongPressDelay = 500; // in milliseconds
  18450. Scene.DoubleClickDelay = 300; // in milliseconds
  18451. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18452. BABYLON.Scene = Scene;
  18453. })(BABYLON || (BABYLON = {}));
  18454. //# sourceMappingURL=babylon.scene.js.map
  18455. var BABYLON;
  18456. (function (BABYLON) {
  18457. var Buffer = (function () {
  18458. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18459. if (engine instanceof BABYLON.Mesh) {
  18460. this._engine = engine.getScene().getEngine();
  18461. }
  18462. else {
  18463. this._engine = engine;
  18464. }
  18465. this._updatable = updatable;
  18466. this._data = data;
  18467. this._strideSize = stride;
  18468. if (!postponeInternalCreation) {
  18469. this.create();
  18470. }
  18471. this._instanced = instanced;
  18472. }
  18473. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18474. // a lot of these parameters are ignored as they are overriden by the buffer
  18475. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18476. };
  18477. // Properties
  18478. Buffer.prototype.isUpdatable = function () {
  18479. return this._updatable;
  18480. };
  18481. Buffer.prototype.getData = function () {
  18482. return this._data;
  18483. };
  18484. Buffer.prototype.getBuffer = function () {
  18485. return this._buffer;
  18486. };
  18487. Buffer.prototype.getStrideSize = function () {
  18488. return this._strideSize;
  18489. };
  18490. Buffer.prototype.getIsInstanced = function () {
  18491. return this._instanced;
  18492. };
  18493. // Methods
  18494. Buffer.prototype.create = function (data) {
  18495. if (!data && this._buffer) {
  18496. return; // nothing to do
  18497. }
  18498. data = data || this._data;
  18499. if (!this._buffer) {
  18500. if (this._updatable) {
  18501. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18502. this._data = data;
  18503. }
  18504. else {
  18505. this._buffer = this._engine.createVertexBuffer(data);
  18506. }
  18507. }
  18508. else if (this._updatable) {
  18509. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18510. this._data = data;
  18511. }
  18512. };
  18513. Buffer.prototype.update = function (data) {
  18514. this.create(data);
  18515. };
  18516. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18517. if (!this._buffer) {
  18518. return;
  18519. }
  18520. if (this._updatable) {
  18521. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18522. this._data = null;
  18523. }
  18524. };
  18525. Buffer.prototype.dispose = function () {
  18526. if (!this._buffer) {
  18527. return;
  18528. }
  18529. if (this._engine._releaseBuffer(this._buffer)) {
  18530. this._buffer = null;
  18531. }
  18532. };
  18533. return Buffer;
  18534. }());
  18535. BABYLON.Buffer = Buffer;
  18536. })(BABYLON || (BABYLON = {}));
  18537. //# sourceMappingURL=babylon.buffer.js.map
  18538. var BABYLON;
  18539. (function (BABYLON) {
  18540. var VertexBuffer = (function () {
  18541. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18542. if (!stride) {
  18543. // Deduce stride from kind
  18544. switch (kind) {
  18545. case VertexBuffer.PositionKind:
  18546. stride = 3;
  18547. break;
  18548. case VertexBuffer.NormalKind:
  18549. stride = 3;
  18550. break;
  18551. case VertexBuffer.UVKind:
  18552. case VertexBuffer.UV2Kind:
  18553. case VertexBuffer.UV3Kind:
  18554. case VertexBuffer.UV4Kind:
  18555. case VertexBuffer.UV5Kind:
  18556. case VertexBuffer.UV6Kind:
  18557. stride = 2;
  18558. break;
  18559. case VertexBuffer.TangentKind:
  18560. case VertexBuffer.ColorKind:
  18561. stride = 4;
  18562. break;
  18563. case VertexBuffer.MatricesIndicesKind:
  18564. case VertexBuffer.MatricesIndicesExtraKind:
  18565. stride = 4;
  18566. break;
  18567. case VertexBuffer.MatricesWeightsKind:
  18568. case VertexBuffer.MatricesWeightsExtraKind:
  18569. stride = 4;
  18570. break;
  18571. }
  18572. }
  18573. if (data instanceof BABYLON.Buffer) {
  18574. if (!stride) {
  18575. stride = data.getStrideSize();
  18576. }
  18577. this._buffer = data;
  18578. this._ownsBuffer = false;
  18579. }
  18580. else {
  18581. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18582. this._ownsBuffer = true;
  18583. }
  18584. this._stride = stride;
  18585. this._offset = offset ? offset : 0;
  18586. this._size = size ? size : stride;
  18587. this._kind = kind;
  18588. }
  18589. /**
  18590. * Returns the kind of the VertexBuffer (string).
  18591. */
  18592. VertexBuffer.prototype.getKind = function () {
  18593. return this._kind;
  18594. };
  18595. // Properties
  18596. /**
  18597. * Boolean : is the VertexBuffer updatable ?
  18598. */
  18599. VertexBuffer.prototype.isUpdatable = function () {
  18600. return this._buffer.isUpdatable();
  18601. };
  18602. /**
  18603. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18604. */
  18605. VertexBuffer.prototype.getData = function () {
  18606. return this._buffer.getData();
  18607. };
  18608. /**
  18609. * Returns the WebGLBuffer associated to the VertexBuffer.
  18610. */
  18611. VertexBuffer.prototype.getBuffer = function () {
  18612. return this._buffer.getBuffer();
  18613. };
  18614. /**
  18615. * Returns the stride of the VertexBuffer (integer).
  18616. */
  18617. VertexBuffer.prototype.getStrideSize = function () {
  18618. return this._stride;
  18619. };
  18620. /**
  18621. * Returns the offset (integer).
  18622. */
  18623. VertexBuffer.prototype.getOffset = function () {
  18624. return this._offset;
  18625. };
  18626. /**
  18627. * Returns the VertexBuffer total size (integer).
  18628. */
  18629. VertexBuffer.prototype.getSize = function () {
  18630. return this._size;
  18631. };
  18632. /**
  18633. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18634. */
  18635. VertexBuffer.prototype.getIsInstanced = function () {
  18636. return this._buffer.getIsInstanced();
  18637. };
  18638. // Methods
  18639. /**
  18640. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18641. * Returns the created WebGLBuffer.
  18642. */
  18643. VertexBuffer.prototype.create = function (data) {
  18644. return this._buffer.create(data);
  18645. };
  18646. /**
  18647. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18648. * Returns the updated WebGLBuffer.
  18649. */
  18650. VertexBuffer.prototype.update = function (data) {
  18651. return this._buffer.update(data);
  18652. };
  18653. /**
  18654. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18655. * Returns the directly updated WebGLBuffer.
  18656. */
  18657. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18658. return this._buffer.updateDirectly(data, offset);
  18659. };
  18660. /**
  18661. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18662. */
  18663. VertexBuffer.prototype.dispose = function () {
  18664. if (this._ownsBuffer) {
  18665. this._buffer.dispose();
  18666. }
  18667. };
  18668. Object.defineProperty(VertexBuffer, "PositionKind", {
  18669. get: function () {
  18670. return VertexBuffer._PositionKind;
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. Object.defineProperty(VertexBuffer, "NormalKind", {
  18676. get: function () {
  18677. return VertexBuffer._NormalKind;
  18678. },
  18679. enumerable: true,
  18680. configurable: true
  18681. });
  18682. Object.defineProperty(VertexBuffer, "TangentKind", {
  18683. get: function () {
  18684. return VertexBuffer._TangentKind;
  18685. },
  18686. enumerable: true,
  18687. configurable: true
  18688. });
  18689. Object.defineProperty(VertexBuffer, "UVKind", {
  18690. get: function () {
  18691. return VertexBuffer._UVKind;
  18692. },
  18693. enumerable: true,
  18694. configurable: true
  18695. });
  18696. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18697. get: function () {
  18698. return VertexBuffer._UV2Kind;
  18699. },
  18700. enumerable: true,
  18701. configurable: true
  18702. });
  18703. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18704. get: function () {
  18705. return VertexBuffer._UV3Kind;
  18706. },
  18707. enumerable: true,
  18708. configurable: true
  18709. });
  18710. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18711. get: function () {
  18712. return VertexBuffer._UV4Kind;
  18713. },
  18714. enumerable: true,
  18715. configurable: true
  18716. });
  18717. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18718. get: function () {
  18719. return VertexBuffer._UV5Kind;
  18720. },
  18721. enumerable: true,
  18722. configurable: true
  18723. });
  18724. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18725. get: function () {
  18726. return VertexBuffer._UV6Kind;
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(VertexBuffer, "ColorKind", {
  18732. get: function () {
  18733. return VertexBuffer._ColorKind;
  18734. },
  18735. enumerable: true,
  18736. configurable: true
  18737. });
  18738. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18739. get: function () {
  18740. return VertexBuffer._MatricesIndicesKind;
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18746. get: function () {
  18747. return VertexBuffer._MatricesWeightsKind;
  18748. },
  18749. enumerable: true,
  18750. configurable: true
  18751. });
  18752. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18753. get: function () {
  18754. return VertexBuffer._MatricesIndicesExtraKind;
  18755. },
  18756. enumerable: true,
  18757. configurable: true
  18758. });
  18759. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18760. get: function () {
  18761. return VertexBuffer._MatricesWeightsExtraKind;
  18762. },
  18763. enumerable: true,
  18764. configurable: true
  18765. });
  18766. return VertexBuffer;
  18767. }());
  18768. // Enums
  18769. VertexBuffer._PositionKind = "position";
  18770. VertexBuffer._NormalKind = "normal";
  18771. VertexBuffer._TangentKind = "tangent";
  18772. VertexBuffer._UVKind = "uv";
  18773. VertexBuffer._UV2Kind = "uv2";
  18774. VertexBuffer._UV3Kind = "uv3";
  18775. VertexBuffer._UV4Kind = "uv4";
  18776. VertexBuffer._UV5Kind = "uv5";
  18777. VertexBuffer._UV6Kind = "uv6";
  18778. VertexBuffer._ColorKind = "color";
  18779. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18780. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18781. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18782. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18783. BABYLON.VertexBuffer = VertexBuffer;
  18784. })(BABYLON || (BABYLON = {}));
  18785. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18786. var BABYLON;
  18787. (function (BABYLON) {
  18788. var BaseTexture = (function () {
  18789. function BaseTexture(scene) {
  18790. this._hasAlpha = false;
  18791. this.getAlphaFromRGB = false;
  18792. this.level = 1;
  18793. this.coordinatesIndex = 0;
  18794. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18795. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18796. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18797. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18798. this.isCube = false;
  18799. this.isRenderTarget = false;
  18800. this.animations = new Array();
  18801. /**
  18802. * An event triggered when the texture is disposed.
  18803. * @type {BABYLON.Observable}
  18804. */
  18805. this.onDisposeObservable = new BABYLON.Observable();
  18806. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18807. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18808. this._scene.textures.push(this);
  18809. this._uid = null;
  18810. }
  18811. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18812. get: function () {
  18813. return this._hasAlpha;
  18814. },
  18815. set: function (value) {
  18816. if (this._hasAlpha === value) {
  18817. return;
  18818. }
  18819. this._hasAlpha = value;
  18820. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18821. },
  18822. enumerable: true,
  18823. configurable: true
  18824. });
  18825. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18826. get: function () {
  18827. return this._coordinatesMode;
  18828. },
  18829. set: function (value) {
  18830. if (this._coordinatesMode === value) {
  18831. return;
  18832. }
  18833. this._coordinatesMode = value;
  18834. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Object.defineProperty(BaseTexture.prototype, "uid", {
  18840. get: function () {
  18841. if (!this._uid) {
  18842. this._uid = BABYLON.Tools.RandomId();
  18843. }
  18844. return this._uid;
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. BaseTexture.prototype.toString = function () {
  18850. return this.name;
  18851. };
  18852. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18853. set: function (callback) {
  18854. if (this._onDisposeObserver) {
  18855. this.onDisposeObservable.remove(this._onDisposeObserver);
  18856. }
  18857. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18858. },
  18859. enumerable: true,
  18860. configurable: true
  18861. });
  18862. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18863. get: function () {
  18864. return true;
  18865. },
  18866. enumerable: true,
  18867. configurable: true
  18868. });
  18869. BaseTexture.prototype.getScene = function () {
  18870. return this._scene;
  18871. };
  18872. BaseTexture.prototype.getTextureMatrix = function () {
  18873. return null;
  18874. };
  18875. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18876. return null;
  18877. };
  18878. BaseTexture.prototype.getInternalTexture = function () {
  18879. return this._texture;
  18880. };
  18881. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18882. return !this.isBlocking || this.isReady();
  18883. };
  18884. BaseTexture.prototype.isReady = function () {
  18885. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18886. this.delayLoad();
  18887. return false;
  18888. }
  18889. if (this._texture) {
  18890. return this._texture.isReady;
  18891. }
  18892. return false;
  18893. };
  18894. BaseTexture.prototype.getSize = function () {
  18895. if (this._texture._width) {
  18896. return new BABYLON.Size(this._texture._width, this._texture._height);
  18897. }
  18898. if (this._texture._size) {
  18899. return new BABYLON.Size(this._texture._size, this._texture._size);
  18900. }
  18901. return BABYLON.Size.Zero();
  18902. };
  18903. BaseTexture.prototype.getBaseSize = function () {
  18904. if (!this.isReady() || !this._texture)
  18905. return BABYLON.Size.Zero();
  18906. if (this._texture._size) {
  18907. return new BABYLON.Size(this._texture._size, this._texture._size);
  18908. }
  18909. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18910. };
  18911. BaseTexture.prototype.scale = function (ratio) {
  18912. };
  18913. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18914. get: function () {
  18915. return false;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18921. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18922. for (var index = 0; index < texturesCache.length; index++) {
  18923. var texturesCacheEntry = texturesCache[index];
  18924. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18925. texturesCache.splice(index, 1);
  18926. return;
  18927. }
  18928. }
  18929. };
  18930. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18931. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18932. for (var index = 0; index < texturesCache.length; index++) {
  18933. var texturesCacheEntry = texturesCache[index];
  18934. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18935. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18936. texturesCacheEntry.references++;
  18937. return texturesCacheEntry;
  18938. }
  18939. }
  18940. }
  18941. return null;
  18942. };
  18943. BaseTexture.prototype.delayLoad = function () {
  18944. };
  18945. BaseTexture.prototype.clone = function () {
  18946. return null;
  18947. };
  18948. BaseTexture.prototype.releaseInternalTexture = function () {
  18949. if (this._texture) {
  18950. this._scene.getEngine().releaseInternalTexture(this._texture);
  18951. delete this._texture;
  18952. }
  18953. };
  18954. BaseTexture.prototype.dispose = function () {
  18955. // Animations
  18956. this.getScene().stopAnimation(this);
  18957. // Remove from scene
  18958. this._scene._removePendingData(this);
  18959. var index = this._scene.textures.indexOf(this);
  18960. if (index >= 0) {
  18961. this._scene.textures.splice(index, 1);
  18962. }
  18963. if (this._texture === undefined) {
  18964. return;
  18965. }
  18966. // Release
  18967. this.releaseInternalTexture();
  18968. // Callback
  18969. this.onDisposeObservable.notifyObservers(this);
  18970. this.onDisposeObservable.clear();
  18971. };
  18972. BaseTexture.prototype.serialize = function () {
  18973. if (!this.name) {
  18974. return null;
  18975. }
  18976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18977. // Animations
  18978. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18979. return serializationObject;
  18980. };
  18981. return BaseTexture;
  18982. }());
  18983. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18984. __decorate([
  18985. BABYLON.serialize()
  18986. ], BaseTexture.prototype, "name", void 0);
  18987. __decorate([
  18988. BABYLON.serialize("hasAlpha")
  18989. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18990. __decorate([
  18991. BABYLON.serialize()
  18992. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18993. __decorate([
  18994. BABYLON.serialize()
  18995. ], BaseTexture.prototype, "level", void 0);
  18996. __decorate([
  18997. BABYLON.serialize()
  18998. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18999. __decorate([
  19000. BABYLON.serialize("coordinatesMode")
  19001. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19002. __decorate([
  19003. BABYLON.serialize()
  19004. ], BaseTexture.prototype, "wrapU", void 0);
  19005. __decorate([
  19006. BABYLON.serialize()
  19007. ], BaseTexture.prototype, "wrapV", void 0);
  19008. __decorate([
  19009. BABYLON.serialize()
  19010. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19011. __decorate([
  19012. BABYLON.serialize()
  19013. ], BaseTexture.prototype, "isCube", void 0);
  19014. __decorate([
  19015. BABYLON.serialize()
  19016. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19017. BABYLON.BaseTexture = BaseTexture;
  19018. })(BABYLON || (BABYLON = {}));
  19019. //# sourceMappingURL=babylon.baseTexture.js.map
  19020. var BABYLON;
  19021. (function (BABYLON) {
  19022. var Texture = (function (_super) {
  19023. __extends(Texture, _super);
  19024. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19025. if (noMipmap === void 0) { noMipmap = false; }
  19026. if (invertY === void 0) { invertY = true; }
  19027. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19028. if (onLoad === void 0) { onLoad = null; }
  19029. if (onError === void 0) { onError = null; }
  19030. if (buffer === void 0) { buffer = null; }
  19031. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19032. var _this = _super.call(this, scene) || this;
  19033. _this.uOffset = 0;
  19034. _this.vOffset = 0;
  19035. _this.uScale = 1.0;
  19036. _this.vScale = 1.0;
  19037. _this.uAng = 0;
  19038. _this.vAng = 0;
  19039. _this.wAng = 0;
  19040. _this._isBlocking = true;
  19041. _this.name = url;
  19042. _this.url = url;
  19043. _this._noMipmap = noMipmap;
  19044. _this._invertY = invertY;
  19045. _this._samplingMode = samplingMode;
  19046. _this._buffer = buffer;
  19047. _this._deleteBuffer = deleteBuffer;
  19048. _this._format = format;
  19049. scene = _this.getScene();
  19050. var load = function () {
  19051. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19052. _this.onLoadObservable.notifyObservers(true);
  19053. }
  19054. if (onLoad) {
  19055. onLoad();
  19056. }
  19057. if (!_this.isBlocking) {
  19058. scene.resetCachedMaterial();
  19059. }
  19060. };
  19061. if (!url) {
  19062. _this._delayedOnLoad = load;
  19063. _this._delayedOnError = onError;
  19064. return _this;
  19065. }
  19066. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19067. if (!_this._texture) {
  19068. if (!scene.useDelayedTextureLoading) {
  19069. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19070. if (deleteBuffer) {
  19071. delete _this._buffer;
  19072. }
  19073. }
  19074. else {
  19075. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19076. _this._delayedOnLoad = load;
  19077. _this._delayedOnError = onError;
  19078. }
  19079. }
  19080. else {
  19081. if (_this._texture.isReady) {
  19082. BABYLON.Tools.SetImmediate(function () { return load(); });
  19083. }
  19084. else {
  19085. _this._texture.onLoadedCallbacks.push(load);
  19086. }
  19087. }
  19088. return _this;
  19089. }
  19090. Object.defineProperty(Texture.prototype, "noMipmap", {
  19091. get: function () {
  19092. return this._noMipmap;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Object.defineProperty(Texture.prototype, "isBlocking", {
  19098. get: function () {
  19099. return this._isBlocking;
  19100. },
  19101. set: function (value) {
  19102. this._isBlocking = value;
  19103. },
  19104. enumerable: true,
  19105. configurable: true
  19106. });
  19107. Texture.prototype.updateURL = function (url) {
  19108. this.url = url;
  19109. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19110. this.delayLoad();
  19111. };
  19112. Texture.prototype.delayLoad = function () {
  19113. var _this = this;
  19114. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19115. return;
  19116. }
  19117. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19118. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19119. if (!this._texture) {
  19120. 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);
  19121. if (this._deleteBuffer) {
  19122. delete this._buffer;
  19123. }
  19124. }
  19125. else {
  19126. if (this._texture.isReady) {
  19127. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19128. }
  19129. else {
  19130. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19131. }
  19132. }
  19133. };
  19134. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19135. if (!this._texture) {
  19136. return;
  19137. }
  19138. this._samplingMode = samplingMode;
  19139. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19140. };
  19141. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19142. x *= this.uScale;
  19143. y *= this.vScale;
  19144. x -= 0.5 * this.uScale;
  19145. y -= 0.5 * this.vScale;
  19146. z -= 0.5;
  19147. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19148. t.x += 0.5 * this.uScale + this.uOffset;
  19149. t.y += 0.5 * this.vScale + this.vOffset;
  19150. t.z += 0.5;
  19151. };
  19152. Texture.prototype.getTextureMatrix = function () {
  19153. if (this.uOffset === this._cachedUOffset &&
  19154. this.vOffset === this._cachedVOffset &&
  19155. this.uScale === this._cachedUScale &&
  19156. this.vScale === this._cachedVScale &&
  19157. this.uAng === this._cachedUAng &&
  19158. this.vAng === this._cachedVAng &&
  19159. this.wAng === this._cachedWAng) {
  19160. return this._cachedTextureMatrix;
  19161. }
  19162. this._cachedUOffset = this.uOffset;
  19163. this._cachedVOffset = this.vOffset;
  19164. this._cachedUScale = this.uScale;
  19165. this._cachedVScale = this.vScale;
  19166. this._cachedUAng = this.uAng;
  19167. this._cachedVAng = this.vAng;
  19168. this._cachedWAng = this.wAng;
  19169. if (!this._cachedTextureMatrix) {
  19170. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19171. this._rowGenerationMatrix = new BABYLON.Matrix();
  19172. this._t0 = BABYLON.Vector3.Zero();
  19173. this._t1 = BABYLON.Vector3.Zero();
  19174. this._t2 = BABYLON.Vector3.Zero();
  19175. }
  19176. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19177. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19178. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19179. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19180. this._t1.subtractInPlace(this._t0);
  19181. this._t2.subtractInPlace(this._t0);
  19182. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19183. this._cachedTextureMatrix.m[0] = this._t1.x;
  19184. this._cachedTextureMatrix.m[1] = this._t1.y;
  19185. this._cachedTextureMatrix.m[2] = this._t1.z;
  19186. this._cachedTextureMatrix.m[4] = this._t2.x;
  19187. this._cachedTextureMatrix.m[5] = this._t2.y;
  19188. this._cachedTextureMatrix.m[6] = this._t2.z;
  19189. this._cachedTextureMatrix.m[8] = this._t0.x;
  19190. this._cachedTextureMatrix.m[9] = this._t0.y;
  19191. this._cachedTextureMatrix.m[10] = this._t0.z;
  19192. return this._cachedTextureMatrix;
  19193. };
  19194. Texture.prototype.getReflectionTextureMatrix = function () {
  19195. if (this.uOffset === this._cachedUOffset &&
  19196. this.vOffset === this._cachedVOffset &&
  19197. this.uScale === this._cachedUScale &&
  19198. this.vScale === this._cachedVScale &&
  19199. this.coordinatesMode === this._cachedCoordinatesMode) {
  19200. return this._cachedTextureMatrix;
  19201. }
  19202. if (!this._cachedTextureMatrix) {
  19203. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19204. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19205. }
  19206. this._cachedCoordinatesMode = this.coordinatesMode;
  19207. switch (this.coordinatesMode) {
  19208. case Texture.PLANAR_MODE:
  19209. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19210. this._cachedTextureMatrix[0] = this.uScale;
  19211. this._cachedTextureMatrix[5] = this.vScale;
  19212. this._cachedTextureMatrix[12] = this.uOffset;
  19213. this._cachedTextureMatrix[13] = this.vOffset;
  19214. break;
  19215. case Texture.PROJECTION_MODE:
  19216. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19217. this._projectionModeMatrix.m[0] = 0.5;
  19218. this._projectionModeMatrix.m[5] = -0.5;
  19219. this._projectionModeMatrix.m[10] = 0.0;
  19220. this._projectionModeMatrix.m[12] = 0.5;
  19221. this._projectionModeMatrix.m[13] = 0.5;
  19222. this._projectionModeMatrix.m[14] = 1.0;
  19223. this._projectionModeMatrix.m[15] = 1.0;
  19224. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19225. break;
  19226. default:
  19227. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19228. break;
  19229. }
  19230. return this._cachedTextureMatrix;
  19231. };
  19232. Texture.prototype.clone = function () {
  19233. var _this = this;
  19234. return BABYLON.SerializationHelper.Clone(function () {
  19235. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19236. }, this);
  19237. };
  19238. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19239. get: function () {
  19240. if (!this._onLoadObservarble) {
  19241. this._onLoadObservarble = new BABYLON.Observable();
  19242. }
  19243. return this._onLoadObservarble;
  19244. },
  19245. enumerable: true,
  19246. configurable: true
  19247. });
  19248. // Statics
  19249. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19250. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19251. if (onLoad === void 0) { onLoad = null; }
  19252. if (onError === void 0) { onError = null; }
  19253. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19254. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19255. };
  19256. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19257. if (parsedTexture.customType) {
  19258. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19259. // Update Sampling Mode
  19260. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19261. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19262. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19263. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19264. }
  19265. }
  19266. return parsedCustomTexture;
  19267. }
  19268. if (parsedTexture.isCube) {
  19269. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19270. }
  19271. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19272. return null;
  19273. }
  19274. var texture = BABYLON.SerializationHelper.Parse(function () {
  19275. if (parsedTexture.mirrorPlane) {
  19276. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19277. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19278. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19279. return mirrorTexture;
  19280. }
  19281. else if (parsedTexture.isRenderTarget) {
  19282. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19283. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19284. return renderTargetTexture;
  19285. }
  19286. else {
  19287. var texture;
  19288. if (parsedTexture.base64String) {
  19289. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19290. }
  19291. else {
  19292. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19293. }
  19294. return texture;
  19295. }
  19296. }, parsedTexture, scene);
  19297. // Update Sampling Mode
  19298. if (parsedTexture.samplingMode) {
  19299. var sampling = parsedTexture.samplingMode;
  19300. if (texture._samplingMode !== sampling) {
  19301. texture.updateSamplingMode(sampling);
  19302. }
  19303. }
  19304. // Animations
  19305. if (parsedTexture.animations) {
  19306. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19307. var parsedAnimation = parsedTexture.animations[animationIndex];
  19308. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19309. }
  19310. }
  19311. return texture;
  19312. };
  19313. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19314. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19315. if (noMipmap === void 0) { noMipmap = false; }
  19316. if (invertY === void 0) { invertY = true; }
  19317. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19318. if (onLoad === void 0) { onLoad = null; }
  19319. if (onError === void 0) { onError = null; }
  19320. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19321. if (name.substr(0, 5) !== "data:") {
  19322. name = "data:" + name;
  19323. }
  19324. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19325. };
  19326. return Texture;
  19327. }(BABYLON.BaseTexture));
  19328. // Constants
  19329. Texture.NEAREST_SAMPLINGMODE = 1;
  19330. Texture.BILINEAR_SAMPLINGMODE = 2;
  19331. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19332. Texture.EXPLICIT_MODE = 0;
  19333. Texture.SPHERICAL_MODE = 1;
  19334. Texture.PLANAR_MODE = 2;
  19335. Texture.CUBIC_MODE = 3;
  19336. Texture.PROJECTION_MODE = 4;
  19337. Texture.SKYBOX_MODE = 5;
  19338. Texture.INVCUBIC_MODE = 6;
  19339. Texture.EQUIRECTANGULAR_MODE = 7;
  19340. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19341. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19342. Texture.CLAMP_ADDRESSMODE = 0;
  19343. Texture.WRAP_ADDRESSMODE = 1;
  19344. Texture.MIRROR_ADDRESSMODE = 2;
  19345. __decorate([
  19346. BABYLON.serialize()
  19347. ], Texture.prototype, "url", void 0);
  19348. __decorate([
  19349. BABYLON.serialize()
  19350. ], Texture.prototype, "uOffset", void 0);
  19351. __decorate([
  19352. BABYLON.serialize()
  19353. ], Texture.prototype, "vOffset", void 0);
  19354. __decorate([
  19355. BABYLON.serialize()
  19356. ], Texture.prototype, "uScale", void 0);
  19357. __decorate([
  19358. BABYLON.serialize()
  19359. ], Texture.prototype, "vScale", void 0);
  19360. __decorate([
  19361. BABYLON.serialize()
  19362. ], Texture.prototype, "uAng", void 0);
  19363. __decorate([
  19364. BABYLON.serialize()
  19365. ], Texture.prototype, "vAng", void 0);
  19366. __decorate([
  19367. BABYLON.serialize()
  19368. ], Texture.prototype, "wAng", void 0);
  19369. __decorate([
  19370. BABYLON.serialize()
  19371. ], Texture.prototype, "isBlocking", null);
  19372. BABYLON.Texture = Texture;
  19373. })(BABYLON || (BABYLON = {}));
  19374. //# sourceMappingURL=babylon.texture.js.map
  19375. var BABYLON;
  19376. (function (BABYLON) {
  19377. var _InstancesBatch = (function () {
  19378. function _InstancesBatch() {
  19379. this.mustReturn = false;
  19380. this.visibleInstances = new Array();
  19381. this.renderSelf = new Array();
  19382. }
  19383. return _InstancesBatch;
  19384. }());
  19385. BABYLON._InstancesBatch = _InstancesBatch;
  19386. var Mesh = (function (_super) {
  19387. __extends(Mesh, _super);
  19388. /**
  19389. * @constructor
  19390. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19391. * @param {Scene} scene The scene to add this mesh to.
  19392. * @param {Node} parent The parent of this mesh, if it has one
  19393. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19394. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19395. * When false, achieved by calling a clone(), also passing False.
  19396. * This will make creation of children, recursive.
  19397. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19398. */
  19399. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19400. if (parent === void 0) { parent = null; }
  19401. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19402. var _this = _super.call(this, name, scene) || this;
  19403. // Events
  19404. /**
  19405. * An event triggered before rendering the mesh
  19406. * @type {BABYLON.Observable}
  19407. */
  19408. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19409. /**
  19410. * An event triggered after rendering the mesh
  19411. * @type {BABYLON.Observable}
  19412. */
  19413. _this.onAfterRenderObservable = new BABYLON.Observable();
  19414. /**
  19415. * An event triggered before drawing the mesh
  19416. * @type {BABYLON.Observable}
  19417. */
  19418. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19419. // Members
  19420. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19421. _this.instances = new Array();
  19422. _this._LODLevels = new Array();
  19423. _this._visibleInstances = {};
  19424. _this._renderIdForInstances = new Array();
  19425. _this._batchCache = new _InstancesBatch();
  19426. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19427. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19428. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19429. // Will be used to save a source mesh reference, If any
  19430. _this._source = null;
  19431. if (source) {
  19432. // Source mesh
  19433. _this._source = source;
  19434. // Geometry
  19435. if (source._geometry) {
  19436. source._geometry.applyToMesh(_this);
  19437. }
  19438. // Deep copy
  19439. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19440. // Parent
  19441. _this.parent = source.parent;
  19442. // Pivot
  19443. _this.setPivotMatrix(source.getPivotMatrix());
  19444. _this.id = name + "." + source.id;
  19445. // Material
  19446. _this.material = source.material;
  19447. var index;
  19448. if (!doNotCloneChildren) {
  19449. // Children
  19450. for (index = 0; index < scene.meshes.length; index++) {
  19451. var mesh = scene.meshes[index];
  19452. if (mesh.parent === source) {
  19453. // doNotCloneChildren is always going to be False
  19454. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19455. }
  19456. }
  19457. }
  19458. // Physics clone
  19459. var physicsEngine = _this.getScene().getPhysicsEngine();
  19460. if (clonePhysicsImpostor && physicsEngine) {
  19461. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19462. if (impostor) {
  19463. _this.physicsImpostor = impostor.clone(_this);
  19464. }
  19465. }
  19466. // Particles
  19467. for (index = 0; index < scene.particleSystems.length; index++) {
  19468. var system = scene.particleSystems[index];
  19469. if (system.emitter === source) {
  19470. system.clone(system.name, _this);
  19471. }
  19472. }
  19473. _this.computeWorldMatrix(true);
  19474. }
  19475. // Parent
  19476. if (parent !== null) {
  19477. _this.parent = parent;
  19478. }
  19479. return _this;
  19480. }
  19481. Object.defineProperty(Mesh, "FRONTSIDE", {
  19482. /**
  19483. * Mesh side orientation : usually the external or front surface
  19484. */
  19485. get: function () {
  19486. return Mesh._FRONTSIDE;
  19487. },
  19488. enumerable: true,
  19489. configurable: true
  19490. });
  19491. Object.defineProperty(Mesh, "BACKSIDE", {
  19492. /**
  19493. * Mesh side orientation : usually the internal or back surface
  19494. */
  19495. get: function () {
  19496. return Mesh._BACKSIDE;
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19502. /**
  19503. * Mesh side orientation : both internal and external or front and back surfaces
  19504. */
  19505. get: function () {
  19506. return Mesh._DOUBLESIDE;
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19512. /**
  19513. * Mesh side orientation : by default, `FRONTSIDE`
  19514. */
  19515. get: function () {
  19516. return Mesh._DEFAULTSIDE;
  19517. },
  19518. enumerable: true,
  19519. configurable: true
  19520. });
  19521. Object.defineProperty(Mesh, "NO_CAP", {
  19522. /**
  19523. * Mesh cap setting : no cap
  19524. */
  19525. get: function () {
  19526. return Mesh._NO_CAP;
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(Mesh, "CAP_START", {
  19532. /**
  19533. * Mesh cap setting : one cap at the beginning of the mesh
  19534. */
  19535. get: function () {
  19536. return Mesh._CAP_START;
  19537. },
  19538. enumerable: true,
  19539. configurable: true
  19540. });
  19541. Object.defineProperty(Mesh, "CAP_END", {
  19542. /**
  19543. * Mesh cap setting : one cap at the end of the mesh
  19544. */
  19545. get: function () {
  19546. return Mesh._CAP_END;
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. Object.defineProperty(Mesh, "CAP_ALL", {
  19552. /**
  19553. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19554. */
  19555. get: function () {
  19556. return Mesh._CAP_ALL;
  19557. },
  19558. enumerable: true,
  19559. configurable: true
  19560. });
  19561. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19562. set: function (callback) {
  19563. if (this._onBeforeDrawObserver) {
  19564. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19565. }
  19566. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19567. },
  19568. enumerable: true,
  19569. configurable: true
  19570. });
  19571. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19572. get: function () {
  19573. return this._morphTargetManager;
  19574. },
  19575. set: function (value) {
  19576. if (this._morphTargetManager === value) {
  19577. return;
  19578. }
  19579. this._morphTargetManager = value;
  19580. this._syncGeometryWithMorphTargetManager();
  19581. },
  19582. enumerable: true,
  19583. configurable: true
  19584. });
  19585. Object.defineProperty(Mesh.prototype, "source", {
  19586. get: function () {
  19587. return this._source;
  19588. },
  19589. enumerable: true,
  19590. configurable: true
  19591. });
  19592. // Methods
  19593. /**
  19594. * Returns the string "Mesh".
  19595. */
  19596. Mesh.prototype.getClassName = function () {
  19597. return "Mesh";
  19598. };
  19599. /**
  19600. * Returns a string.
  19601. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19602. */
  19603. Mesh.prototype.toString = function (fullDetails) {
  19604. var ret = _super.prototype.toString.call(this, fullDetails);
  19605. ret += ", n vertices: " + this.getTotalVertices();
  19606. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19607. if (this.animations) {
  19608. for (var i = 0; i < this.animations.length; i++) {
  19609. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19610. }
  19611. }
  19612. if (fullDetails) {
  19613. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19614. }
  19615. return ret;
  19616. };
  19617. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19618. /**
  19619. * True if the mesh has some Levels Of Details (LOD).
  19620. * Returns a boolean.
  19621. */
  19622. get: function () {
  19623. return this._LODLevels.length > 0;
  19624. },
  19625. enumerable: true,
  19626. configurable: true
  19627. });
  19628. Mesh.prototype._sortLODLevels = function () {
  19629. this._LODLevels.sort(function (a, b) {
  19630. if (a.distance < b.distance) {
  19631. return 1;
  19632. }
  19633. if (a.distance > b.distance) {
  19634. return -1;
  19635. }
  19636. return 0;
  19637. });
  19638. };
  19639. /**
  19640. * Add a mesh as LOD level triggered at the given distance.
  19641. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19642. * @param {number} distance The distance from the center of the object to show this level
  19643. * @param {Mesh} mesh The mesh to be added as LOD level
  19644. * @return {Mesh} This mesh (for chaining)
  19645. */
  19646. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19647. if (mesh && mesh._masterMesh) {
  19648. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19649. return this;
  19650. }
  19651. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19652. this._LODLevels.push(level);
  19653. if (mesh) {
  19654. mesh._masterMesh = this;
  19655. }
  19656. this._sortLODLevels();
  19657. return this;
  19658. };
  19659. /**
  19660. * Returns the LOD level mesh at the passed distance or null if not found.
  19661. * It is related to the method `addLODLevel(distance, mesh)`.
  19662. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19663. * Returns an object Mesh or `null`.
  19664. */
  19665. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19666. for (var index = 0; index < this._LODLevels.length; index++) {
  19667. var level = this._LODLevels[index];
  19668. if (level.distance === distance) {
  19669. return level.mesh;
  19670. }
  19671. }
  19672. return null;
  19673. };
  19674. /**
  19675. * Remove a mesh from the LOD array
  19676. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19677. * @param {Mesh} mesh The mesh to be removed.
  19678. * @return {Mesh} This mesh (for chaining)
  19679. */
  19680. Mesh.prototype.removeLODLevel = function (mesh) {
  19681. for (var index = 0; index < this._LODLevels.length; index++) {
  19682. if (this._LODLevels[index].mesh === mesh) {
  19683. this._LODLevels.splice(index, 1);
  19684. if (mesh) {
  19685. mesh._masterMesh = null;
  19686. }
  19687. }
  19688. }
  19689. this._sortLODLevels();
  19690. return this;
  19691. };
  19692. /**
  19693. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19694. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19695. */
  19696. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19697. if (!this._LODLevels || this._LODLevels.length === 0) {
  19698. return this;
  19699. }
  19700. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19701. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19702. if (this.onLODLevelSelection) {
  19703. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19704. }
  19705. return this;
  19706. }
  19707. for (var index = 0; index < this._LODLevels.length; index++) {
  19708. var level = this._LODLevels[index];
  19709. if (level.distance < distanceToCamera) {
  19710. if (level.mesh) {
  19711. level.mesh._preActivate();
  19712. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19713. }
  19714. if (this.onLODLevelSelection) {
  19715. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19716. }
  19717. return level.mesh;
  19718. }
  19719. }
  19720. if (this.onLODLevelSelection) {
  19721. this.onLODLevelSelection(distanceToCamera, this, this);
  19722. }
  19723. return this;
  19724. };
  19725. Object.defineProperty(Mesh.prototype, "geometry", {
  19726. /**
  19727. * Returns the mesh internal Geometry object.
  19728. */
  19729. get: function () {
  19730. return this._geometry;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. /**
  19736. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19737. */
  19738. Mesh.prototype.getTotalVertices = function () {
  19739. if (!this._geometry) {
  19740. return 0;
  19741. }
  19742. return this._geometry.getTotalVertices();
  19743. };
  19744. /**
  19745. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19746. * 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.
  19747. * You can force the copy with forceCopy === true
  19748. * Returns null if the mesh has no geometry or no vertex buffer.
  19749. * Possible `kind` values :
  19750. * - BABYLON.VertexBuffer.PositionKind
  19751. * - BABYLON.VertexBuffer.UVKind
  19752. * - BABYLON.VertexBuffer.UV2Kind
  19753. * - BABYLON.VertexBuffer.UV3Kind
  19754. * - BABYLON.VertexBuffer.UV4Kind
  19755. * - BABYLON.VertexBuffer.UV5Kind
  19756. * - BABYLON.VertexBuffer.UV6Kind
  19757. * - BABYLON.VertexBuffer.ColorKind
  19758. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19759. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19760. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19761. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19762. */
  19763. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19764. if (!this._geometry) {
  19765. return null;
  19766. }
  19767. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19768. };
  19769. /**
  19770. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19771. * Returns `undefined` if the mesh has no geometry.
  19772. * Possible `kind` values :
  19773. * - BABYLON.VertexBuffer.PositionKind
  19774. * - BABYLON.VertexBuffer.UVKind
  19775. * - BABYLON.VertexBuffer.UV2Kind
  19776. * - BABYLON.VertexBuffer.UV3Kind
  19777. * - BABYLON.VertexBuffer.UV4Kind
  19778. * - BABYLON.VertexBuffer.UV5Kind
  19779. * - BABYLON.VertexBuffer.UV6Kind
  19780. * - BABYLON.VertexBuffer.ColorKind
  19781. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19782. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19783. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19784. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19785. */
  19786. Mesh.prototype.getVertexBuffer = function (kind) {
  19787. if (!this._geometry) {
  19788. return undefined;
  19789. }
  19790. return this._geometry.getVertexBuffer(kind);
  19791. };
  19792. /**
  19793. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19794. * Possible `kind` values :
  19795. * - BABYLON.VertexBuffer.PositionKind
  19796. * - BABYLON.VertexBuffer.UVKind
  19797. * - BABYLON.VertexBuffer.UV2Kind
  19798. * - BABYLON.VertexBuffer.UV3Kind
  19799. * - BABYLON.VertexBuffer.UV4Kind
  19800. * - BABYLON.VertexBuffer.UV5Kind
  19801. * - BABYLON.VertexBuffer.UV6Kind
  19802. * - BABYLON.VertexBuffer.ColorKind
  19803. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19804. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19805. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19806. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19807. */
  19808. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19809. if (!this._geometry) {
  19810. if (this._delayInfo) {
  19811. return this._delayInfo.indexOf(kind) !== -1;
  19812. }
  19813. return false;
  19814. }
  19815. return this._geometry.isVerticesDataPresent(kind);
  19816. };
  19817. /**
  19818. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19819. * Possible `kind` values :
  19820. * - BABYLON.VertexBuffer.PositionKind
  19821. * - BABYLON.VertexBuffer.UVKind
  19822. * - BABYLON.VertexBuffer.UV2Kind
  19823. * - BABYLON.VertexBuffer.UV3Kind
  19824. * - BABYLON.VertexBuffer.UV4Kind
  19825. * - BABYLON.VertexBuffer.UV5Kind
  19826. * - BABYLON.VertexBuffer.UV6Kind
  19827. * - BABYLON.VertexBuffer.ColorKind
  19828. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19829. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19830. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19831. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19832. */
  19833. Mesh.prototype.getVerticesDataKinds = function () {
  19834. if (!this._geometry) {
  19835. var result = [];
  19836. if (this._delayInfo) {
  19837. this._delayInfo.forEach(function (kind, index, array) {
  19838. result.push(kind);
  19839. });
  19840. }
  19841. return result;
  19842. }
  19843. return this._geometry.getVerticesDataKinds();
  19844. };
  19845. /**
  19846. * Returns a positive integer : the total number of indices in this mesh geometry.
  19847. * Returns zero if the mesh has no geometry.
  19848. */
  19849. Mesh.prototype.getTotalIndices = function () {
  19850. if (!this._geometry) {
  19851. return 0;
  19852. }
  19853. return this._geometry.getTotalIndices();
  19854. };
  19855. /**
  19856. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19857. * 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.
  19858. * Returns an empty array if the mesh has no geometry.
  19859. */
  19860. Mesh.prototype.getIndices = function (copyWhenShared) {
  19861. if (!this._geometry) {
  19862. return [];
  19863. }
  19864. return this._geometry.getIndices(copyWhenShared);
  19865. };
  19866. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19867. get: function () {
  19868. return this._masterMesh !== null && this._masterMesh !== undefined;
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. /**
  19874. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19875. */
  19876. Mesh.prototype.isReady = function () {
  19877. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19878. return false;
  19879. }
  19880. return _super.prototype.isReady.call(this);
  19881. };
  19882. /**
  19883. * Boolean : true if the mesh has been disposed.
  19884. */
  19885. Mesh.prototype.isDisposed = function () {
  19886. return this._isDisposed;
  19887. };
  19888. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19889. get: function () {
  19890. return this._sideOrientation;
  19891. },
  19892. /**
  19893. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19894. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19895. */
  19896. set: function (sideO) {
  19897. this._sideOrientation = sideO;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19903. /**
  19904. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19905. * This property is pertinent only for updatable parametric shapes.
  19906. */
  19907. get: function () {
  19908. return this._areNormalsFrozen;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. /**
  19914. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19915. * It has no effect at all on other shapes.
  19916. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19917. * Returns the Mesh.
  19918. */
  19919. Mesh.prototype.freezeNormals = function () {
  19920. this._areNormalsFrozen = true;
  19921. return this;
  19922. };
  19923. /**
  19924. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19925. * It has no effect at all on other shapes.
  19926. * It reactivates the mesh normals computation if it was previously frozen.
  19927. * Returns the Mesh.
  19928. */
  19929. Mesh.prototype.unfreezeNormals = function () {
  19930. this._areNormalsFrozen = false;
  19931. return this;
  19932. };
  19933. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19934. /**
  19935. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19936. */
  19937. set: function (count) {
  19938. this._overridenInstanceCount = count;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. // Methods
  19944. Mesh.prototype._preActivate = function () {
  19945. var sceneRenderId = this.getScene().getRenderId();
  19946. if (this._preActivateId === sceneRenderId) {
  19947. return this;
  19948. }
  19949. this._preActivateId = sceneRenderId;
  19950. this._visibleInstances = null;
  19951. return this;
  19952. };
  19953. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19954. if (this._visibleInstances) {
  19955. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19956. }
  19957. return this;
  19958. };
  19959. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19960. if (!this._visibleInstances) {
  19961. this._visibleInstances = {};
  19962. this._visibleInstances.defaultRenderId = renderId;
  19963. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19964. }
  19965. if (!this._visibleInstances[renderId]) {
  19966. this._visibleInstances[renderId] = new Array();
  19967. }
  19968. this._visibleInstances[renderId].push(instance);
  19969. return this;
  19970. };
  19971. /**
  19972. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19973. * This means the mesh underlying bounding box and sphere are recomputed.
  19974. * Returns the Mesh.
  19975. */
  19976. Mesh.prototype.refreshBoundingInfo = function () {
  19977. if (this._boundingInfo.isLocked) {
  19978. return;
  19979. }
  19980. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19981. if (data) {
  19982. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19983. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19984. }
  19985. if (this.subMeshes) {
  19986. for (var index = 0; index < this.subMeshes.length; index++) {
  19987. this.subMeshes[index].refreshBoundingInfo();
  19988. }
  19989. }
  19990. this._updateBoundingInfo();
  19991. return this;
  19992. };
  19993. Mesh.prototype._createGlobalSubMesh = function () {
  19994. var totalVertices = this.getTotalVertices();
  19995. if (!totalVertices || !this.getIndices()) {
  19996. return null;
  19997. }
  19998. this.releaseSubMeshes();
  19999. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20000. };
  20001. Mesh.prototype.subdivide = function (count) {
  20002. if (count < 1) {
  20003. return;
  20004. }
  20005. var totalIndices = this.getTotalIndices();
  20006. var subdivisionSize = (totalIndices / count) | 0;
  20007. var offset = 0;
  20008. // Ensure that subdivisionSize is a multiple of 3
  20009. while (subdivisionSize % 3 !== 0) {
  20010. subdivisionSize++;
  20011. }
  20012. this.releaseSubMeshes();
  20013. for (var index = 0; index < count; index++) {
  20014. if (offset >= totalIndices) {
  20015. break;
  20016. }
  20017. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20018. offset += subdivisionSize;
  20019. }
  20020. this.synchronizeInstances();
  20021. };
  20022. /**
  20023. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20024. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20025. * The `data` are either a numeric array either a Float32Array.
  20026. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20027. * 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).
  20028. * Note that a new underlying VertexBuffer object is created each call.
  20029. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20030. *
  20031. * Possible `kind` values :
  20032. * - BABYLON.VertexBuffer.PositionKind
  20033. * - BABYLON.VertexBuffer.UVKind
  20034. * - BABYLON.VertexBuffer.UV2Kind
  20035. * - BABYLON.VertexBuffer.UV3Kind
  20036. * - BABYLON.VertexBuffer.UV4Kind
  20037. * - BABYLON.VertexBuffer.UV5Kind
  20038. * - BABYLON.VertexBuffer.UV6Kind
  20039. * - BABYLON.VertexBuffer.ColorKind
  20040. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20041. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20042. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20043. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20044. *
  20045. * Returns the Mesh.
  20046. */
  20047. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20048. if (!this._geometry) {
  20049. var vertexData = new BABYLON.VertexData();
  20050. vertexData.set(data, kind);
  20051. var scene = this.getScene();
  20052. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20053. }
  20054. else {
  20055. this._geometry.setVerticesData(kind, data, updatable, stride);
  20056. }
  20057. return this;
  20058. };
  20059. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20060. if (updatable === void 0) { updatable = true; }
  20061. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20062. return;
  20063. }
  20064. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20065. };
  20066. /**
  20067. * Sets the mesh VertexBuffer.
  20068. * Returns the Mesh.
  20069. */
  20070. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20071. if (!this._geometry) {
  20072. var scene = this.getScene();
  20073. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20074. }
  20075. this._geometry.setVerticesBuffer(buffer);
  20076. return this;
  20077. };
  20078. /**
  20079. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20080. * If the mesh has no geometry, it is simply returned as it is.
  20081. * The `data` are either a numeric array either a Float32Array.
  20082. * No new underlying VertexBuffer object is created.
  20083. * 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.
  20084. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20085. *
  20086. * Possible `kind` values :
  20087. * - BABYLON.VertexBuffer.PositionKind
  20088. * - BABYLON.VertexBuffer.UVKind
  20089. * - BABYLON.VertexBuffer.UV2Kind
  20090. * - BABYLON.VertexBuffer.UV3Kind
  20091. * - BABYLON.VertexBuffer.UV4Kind
  20092. * - BABYLON.VertexBuffer.UV5Kind
  20093. * - BABYLON.VertexBuffer.UV6Kind
  20094. * - BABYLON.VertexBuffer.ColorKind
  20095. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20096. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20097. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20098. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20099. *
  20100. * Returns the Mesh.
  20101. */
  20102. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20103. if (!this._geometry) {
  20104. return;
  20105. }
  20106. if (!makeItUnique) {
  20107. this._geometry.updateVerticesData(kind, data, updateExtends);
  20108. }
  20109. else {
  20110. this.makeGeometryUnique();
  20111. this.updateVerticesData(kind, data, updateExtends, false);
  20112. }
  20113. return this;
  20114. };
  20115. /**
  20116. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20117. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20118. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20119. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20120. * Returns the Mesh.
  20121. */
  20122. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20123. if (computeNormals === void 0) { computeNormals = true; }
  20124. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20125. positionFunction(positions);
  20126. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20127. if (computeNormals) {
  20128. var indices = this.getIndices();
  20129. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20130. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20131. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20132. }
  20133. return this;
  20134. };
  20135. /**
  20136. * Creates a un-shared specific occurence of the geometry for the mesh.
  20137. * Returns the Mesh.
  20138. */
  20139. Mesh.prototype.makeGeometryUnique = function () {
  20140. if (!this._geometry) {
  20141. return;
  20142. }
  20143. var oldGeometry = this._geometry;
  20144. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20145. oldGeometry.releaseForMesh(this, true);
  20146. geometry.applyToMesh(this);
  20147. return this;
  20148. };
  20149. /**
  20150. * Sets the mesh indices.
  20151. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20152. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20153. * This method creates a new index buffer each call.
  20154. * Returns the Mesh.
  20155. */
  20156. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20157. if (!this._geometry) {
  20158. var vertexData = new BABYLON.VertexData();
  20159. vertexData.indices = indices;
  20160. var scene = this.getScene();
  20161. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20162. }
  20163. else {
  20164. this._geometry.setIndices(indices, totalVertices);
  20165. }
  20166. return this;
  20167. };
  20168. /**
  20169. * Invert the geometry to move from a right handed system to a left handed one.
  20170. * Returns the Mesh.
  20171. */
  20172. Mesh.prototype.toLeftHanded = function () {
  20173. if (!this._geometry) {
  20174. return;
  20175. }
  20176. this._geometry.toLeftHanded();
  20177. return this;
  20178. };
  20179. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20180. var engine = this.getScene().getEngine();
  20181. // Wireframe
  20182. var indexToBind;
  20183. if (this._unIndexed) {
  20184. indexToBind = null;
  20185. }
  20186. else {
  20187. switch (fillMode) {
  20188. case BABYLON.Material.PointFillMode:
  20189. indexToBind = null;
  20190. break;
  20191. case BABYLON.Material.WireFrameFillMode:
  20192. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20193. break;
  20194. default:
  20195. case BABYLON.Material.TriangleFillMode:
  20196. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20197. break;
  20198. }
  20199. }
  20200. // VBOs
  20201. this._geometry._bind(effect, indexToBind);
  20202. return this;
  20203. };
  20204. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20205. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20206. return this;
  20207. }
  20208. this.onBeforeDrawObservable.notifyObservers(this);
  20209. var engine = this.getScene().getEngine();
  20210. // Draw order
  20211. switch (fillMode) {
  20212. case BABYLON.Material.PointFillMode:
  20213. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20214. break;
  20215. case BABYLON.Material.WireFrameFillMode:
  20216. if (this._unIndexed) {
  20217. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20218. }
  20219. else {
  20220. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20221. }
  20222. break;
  20223. default:
  20224. if (this._unIndexed) {
  20225. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20226. }
  20227. else {
  20228. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20229. }
  20230. }
  20231. return this;
  20232. };
  20233. /**
  20234. * Registers for this mesh a javascript function called just before the rendering process.
  20235. * This function is passed the current mesh.
  20236. * Return the Mesh.
  20237. */
  20238. Mesh.prototype.registerBeforeRender = function (func) {
  20239. this.onBeforeRenderObservable.add(func);
  20240. return this;
  20241. };
  20242. /**
  20243. * Disposes a previously registered javascript function called before the rendering.
  20244. * This function is passed the current mesh.
  20245. * Returns the Mesh.
  20246. */
  20247. Mesh.prototype.unregisterBeforeRender = function (func) {
  20248. this.onBeforeRenderObservable.removeCallback(func);
  20249. return this;
  20250. };
  20251. /**
  20252. * Registers for this mesh a javascript function called just after the rendering is complete.
  20253. * This function is passed the current mesh.
  20254. * Returns the Mesh.
  20255. */
  20256. Mesh.prototype.registerAfterRender = function (func) {
  20257. this.onAfterRenderObservable.add(func);
  20258. return this;
  20259. };
  20260. /**
  20261. * Disposes a previously registered javascript function called after the rendering.
  20262. * This function is passed the current mesh.
  20263. * Return the Mesh.
  20264. */
  20265. Mesh.prototype.unregisterAfterRender = function (func) {
  20266. this.onAfterRenderObservable.removeCallback(func);
  20267. return this;
  20268. };
  20269. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20270. var scene = this.getScene();
  20271. this._batchCache.mustReturn = false;
  20272. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20273. this._batchCache.visibleInstances[subMeshId] = null;
  20274. if (this._visibleInstances) {
  20275. var currentRenderId = scene.getRenderId();
  20276. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20277. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20278. var selfRenderId = this._renderId;
  20279. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20280. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20281. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20282. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20283. }
  20284. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20285. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20286. this._batchCache.mustReturn = true;
  20287. return this._batchCache;
  20288. }
  20289. if (currentRenderId !== selfRenderId) {
  20290. this._batchCache.renderSelf[subMeshId] = false;
  20291. }
  20292. }
  20293. this._renderIdForInstances[subMeshId] = currentRenderId;
  20294. }
  20295. return this._batchCache;
  20296. };
  20297. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20298. var visibleInstances = batch.visibleInstances[subMesh._id];
  20299. var matricesCount = visibleInstances.length + 1;
  20300. var bufferSize = matricesCount * 16 * 4;
  20301. var currentInstancesBufferSize = this._instancesBufferSize;
  20302. var instancesBuffer = this._instancesBuffer;
  20303. while (this._instancesBufferSize < bufferSize) {
  20304. this._instancesBufferSize *= 2;
  20305. }
  20306. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20307. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20308. }
  20309. var offset = 0;
  20310. var instancesCount = 0;
  20311. var world = this.getWorldMatrix();
  20312. if (batch.renderSelf[subMesh._id]) {
  20313. world.copyToArray(this._instancesData, offset);
  20314. offset += 16;
  20315. instancesCount++;
  20316. }
  20317. if (visibleInstances) {
  20318. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20319. var instance = visibleInstances[instanceIndex];
  20320. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20321. offset += 16;
  20322. instancesCount++;
  20323. }
  20324. }
  20325. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20326. if (instancesBuffer) {
  20327. instancesBuffer.dispose();
  20328. }
  20329. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20330. this._instancesBuffer = instancesBuffer;
  20331. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20332. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20333. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20334. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20335. }
  20336. else {
  20337. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20338. }
  20339. this.geometry._bind(effect);
  20340. this._draw(subMesh, fillMode, instancesCount);
  20341. engine.unbindInstanceAttributes();
  20342. return this;
  20343. };
  20344. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20345. var scene = this.getScene();
  20346. var engine = scene.getEngine();
  20347. if (hardwareInstancedRendering) {
  20348. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20349. }
  20350. else {
  20351. if (batch.renderSelf[subMesh._id]) {
  20352. // Draw
  20353. if (onBeforeDraw) {
  20354. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20355. }
  20356. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20357. }
  20358. if (batch.visibleInstances[subMesh._id]) {
  20359. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20360. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20361. // World
  20362. var world = instance.getWorldMatrix();
  20363. if (onBeforeDraw) {
  20364. onBeforeDraw(true, world, effectiveMaterial);
  20365. }
  20366. // Draw
  20367. this._draw(subMesh, fillMode);
  20368. }
  20369. }
  20370. }
  20371. return this;
  20372. };
  20373. /**
  20374. * Triggers the draw call for the mesh.
  20375. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20376. * Returns the Mesh.
  20377. */
  20378. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20379. var scene = this.getScene();
  20380. // Managing instances
  20381. var batch = this._getInstancesRenderList(subMesh._id);
  20382. if (batch.mustReturn) {
  20383. return this;
  20384. }
  20385. // Checking geometry state
  20386. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20387. return this;
  20388. }
  20389. var callbackIndex;
  20390. this.onBeforeRenderObservable.notifyObservers(this);
  20391. var engine = scene.getEngine();
  20392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20393. // Material
  20394. var effectiveMaterial = subMesh.getMaterial();
  20395. if (!effectiveMaterial) {
  20396. return this;
  20397. }
  20398. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20399. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20400. return this;
  20401. }
  20402. }
  20403. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20404. return this;
  20405. }
  20406. // Alpha mode
  20407. if (enableAlphaMode) {
  20408. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20409. }
  20410. // Outline - step 1
  20411. var savedDepthWrite = engine.getDepthWrite();
  20412. if (this.renderOutline) {
  20413. engine.setDepthWrite(false);
  20414. scene.getOutlineRenderer().render(subMesh, batch);
  20415. engine.setDepthWrite(savedDepthWrite);
  20416. }
  20417. var effect;
  20418. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20419. effect = subMesh.effect;
  20420. }
  20421. else {
  20422. effect = effectiveMaterial.getEffect();
  20423. }
  20424. effectiveMaterial._preBind(effect);
  20425. // Bind
  20426. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20427. this._bind(subMesh, effect, fillMode);
  20428. var world = this.getWorldMatrix();
  20429. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20430. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20431. }
  20432. else {
  20433. effectiveMaterial.bind(world, this);
  20434. }
  20435. // Draw
  20436. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20437. // Unbind
  20438. effectiveMaterial.unbind();
  20439. // Outline - step 2
  20440. if (this.renderOutline && savedDepthWrite) {
  20441. engine.setDepthWrite(true);
  20442. engine.setColorWrite(false);
  20443. scene.getOutlineRenderer().render(subMesh, batch);
  20444. engine.setColorWrite(true);
  20445. }
  20446. // Overlay
  20447. if (this.renderOverlay) {
  20448. var currentMode = engine.getAlphaMode();
  20449. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20450. scene.getOutlineRenderer().render(subMesh, batch, true);
  20451. engine.setAlphaMode(currentMode);
  20452. }
  20453. this.onAfterRenderObservable.notifyObservers(this);
  20454. return this;
  20455. };
  20456. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20457. if (isInstance) {
  20458. effectiveMaterial.bindOnlyWorldMatrix(world);
  20459. }
  20460. return this;
  20461. };
  20462. /**
  20463. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20464. */
  20465. Mesh.prototype.getEmittedParticleSystems = function () {
  20466. var results = new Array();
  20467. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20468. var particleSystem = this.getScene().particleSystems[index];
  20469. if (particleSystem.emitter === this) {
  20470. results.push(particleSystem);
  20471. }
  20472. }
  20473. return results;
  20474. };
  20475. /**
  20476. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20477. */
  20478. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20479. var results = new Array();
  20480. var descendants = this.getDescendants();
  20481. descendants.push(this);
  20482. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20483. var particleSystem = this.getScene().particleSystems[index];
  20484. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20485. results.push(particleSystem);
  20486. }
  20487. }
  20488. return results;
  20489. };
  20490. Mesh.prototype._checkDelayState = function () {
  20491. var scene = this.getScene();
  20492. if (this._geometry) {
  20493. this._geometry.load(scene);
  20494. }
  20495. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20497. this._queueLoad(this, scene);
  20498. }
  20499. return this;
  20500. };
  20501. Mesh.prototype._queueLoad = function (mesh, scene) {
  20502. var _this = this;
  20503. scene._addPendingData(mesh);
  20504. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20505. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20506. if (data instanceof ArrayBuffer) {
  20507. _this._delayLoadingFunction(data, _this);
  20508. }
  20509. else {
  20510. _this._delayLoadingFunction(JSON.parse(data), _this);
  20511. }
  20512. _this.instances.forEach(function (instance) {
  20513. instance._syncSubMeshes();
  20514. });
  20515. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20516. scene._removePendingData(_this);
  20517. }, function () { }, scene.database, getBinaryData);
  20518. return this;
  20519. };
  20520. /**
  20521. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20522. */
  20523. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20524. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20525. return false;
  20526. }
  20527. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20528. return false;
  20529. }
  20530. this._checkDelayState();
  20531. return true;
  20532. };
  20533. /**
  20534. * Sets the mesh material by the material or multiMaterial `id` property.
  20535. * The material `id` is a string identifying the material or the multiMaterial.
  20536. * This method returns the Mesh.
  20537. */
  20538. Mesh.prototype.setMaterialByID = function (id) {
  20539. var materials = this.getScene().materials;
  20540. var index;
  20541. for (index = materials.length - 1; index > -1; index--) {
  20542. if (materials[index].id === id) {
  20543. this.material = materials[index];
  20544. return this;
  20545. }
  20546. }
  20547. // Multi
  20548. var multiMaterials = this.getScene().multiMaterials;
  20549. for (index = multiMaterials.length - 1; index > -1; index--) {
  20550. if (multiMaterials[index].id === id) {
  20551. this.material = multiMaterials[index];
  20552. return this;
  20553. }
  20554. }
  20555. return this;
  20556. };
  20557. /**
  20558. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20559. */
  20560. Mesh.prototype.getAnimatables = function () {
  20561. var results = [];
  20562. if (this.material) {
  20563. results.push(this.material);
  20564. }
  20565. if (this.skeleton) {
  20566. results.push(this.skeleton);
  20567. }
  20568. return results;
  20569. };
  20570. /**
  20571. * Modifies the mesh geometry according to the passed transformation matrix.
  20572. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20573. * The mesh normals are modified accordingly the same transformation.
  20574. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20575. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20576. * Returns the Mesh.
  20577. */
  20578. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20579. // Position
  20580. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20581. return this;
  20582. }
  20583. var submeshes = this.subMeshes.splice(0);
  20584. this._resetPointsArrayCache();
  20585. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20586. var temp = [];
  20587. var index;
  20588. for (index = 0; index < data.length; index += 3) {
  20589. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20590. }
  20591. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20592. // Normals
  20593. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20594. return this;
  20595. }
  20596. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20597. temp = [];
  20598. for (index = 0; index < data.length; index += 3) {
  20599. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20600. }
  20601. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20602. // flip faces?
  20603. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20604. this.flipFaces();
  20605. }
  20606. // Restore submeshes
  20607. this.releaseSubMeshes();
  20608. this.subMeshes = submeshes;
  20609. return this;
  20610. };
  20611. /**
  20612. * Modifies the mesh geometry according to its own current World Matrix.
  20613. * The mesh World Matrix is then reset.
  20614. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20615. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20616. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20617. * Returns the Mesh.
  20618. */
  20619. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20620. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20621. this.scaling.copyFromFloats(1, 1, 1);
  20622. this.position.copyFromFloats(0, 0, 0);
  20623. this.rotation.copyFromFloats(0, 0, 0);
  20624. //only if quaternion is already set
  20625. if (this.rotationQuaternion) {
  20626. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20627. }
  20628. this._worldMatrix = BABYLON.Matrix.Identity();
  20629. return this;
  20630. };
  20631. Object.defineProperty(Mesh.prototype, "_positions", {
  20632. // Cache
  20633. get: function () {
  20634. if (this._geometry) {
  20635. return this._geometry._positions;
  20636. }
  20637. return null;
  20638. },
  20639. enumerable: true,
  20640. configurable: true
  20641. });
  20642. Mesh.prototype._resetPointsArrayCache = function () {
  20643. if (this._geometry) {
  20644. this._geometry._resetPointsArrayCache();
  20645. }
  20646. return this;
  20647. };
  20648. Mesh.prototype._generatePointsArray = function () {
  20649. if (this._geometry) {
  20650. return this._geometry._generatePointsArray();
  20651. }
  20652. return false;
  20653. };
  20654. /**
  20655. * Returns a new Mesh object generated from the current mesh properties.
  20656. * This method must not get confused with createInstance().
  20657. * The parameter `name` is a string, the name given to the new mesh.
  20658. * The optional parameter `newParent` can be any Node object (default `null`).
  20659. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20660. * 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.
  20661. */
  20662. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20663. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20664. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20665. };
  20666. /**
  20667. * Disposes the mesh.
  20668. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20669. */
  20670. Mesh.prototype.dispose = function (doNotRecurse) {
  20671. var _this = this;
  20672. this.morphTargetManager = undefined;
  20673. if (this._geometry) {
  20674. this._geometry.releaseForMesh(this, true);
  20675. }
  20676. // Sources
  20677. var meshes = this.getScene().meshes;
  20678. meshes.forEach(function (mesh) {
  20679. if (mesh._source && mesh._source === _this) {
  20680. mesh._source = null;
  20681. }
  20682. });
  20683. this._source = null;
  20684. // Instances
  20685. if (this._instancesBuffer) {
  20686. this._instancesBuffer.dispose();
  20687. this._instancesBuffer = null;
  20688. }
  20689. while (this.instances.length) {
  20690. this.instances[0].dispose();
  20691. }
  20692. // Highlight layers.
  20693. var highlightLayers = this.getScene().highlightLayers;
  20694. for (var i = 0; i < highlightLayers.length; i++) {
  20695. var highlightLayer = highlightLayers[i];
  20696. if (highlightLayer) {
  20697. highlightLayer.removeMesh(this);
  20698. highlightLayer.removeExcludedMesh(this);
  20699. }
  20700. }
  20701. _super.prototype.dispose.call(this, doNotRecurse);
  20702. };
  20703. /**
  20704. * Modifies the mesh geometry according to a displacement map.
  20705. * 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.
  20706. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20707. * This method returns nothing.
  20708. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20709. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20710. * 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.
  20711. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20712. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20713. *
  20714. * Returns the Mesh.
  20715. */
  20716. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20717. var _this = this;
  20718. var scene = this.getScene();
  20719. var onload = function (img) {
  20720. // Getting height map data
  20721. var canvas = document.createElement("canvas");
  20722. var context = canvas.getContext("2d");
  20723. var heightMapWidth = img.width;
  20724. var heightMapHeight = img.height;
  20725. canvas.width = heightMapWidth;
  20726. canvas.height = heightMapHeight;
  20727. context.drawImage(img, 0, 0);
  20728. // Create VertexData from map data
  20729. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20730. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20731. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20732. //execute success callback, if set
  20733. if (onSuccess) {
  20734. onSuccess(_this);
  20735. }
  20736. };
  20737. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20738. return this;
  20739. };
  20740. /**
  20741. * Modifies the mesh geometry according to a displacementMap buffer.
  20742. * 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.
  20743. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20744. * This method returns nothing.
  20745. * 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.
  20746. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20747. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20748. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20749. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20750. *
  20751. * Returns the Mesh.
  20752. */
  20753. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20754. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20755. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20756. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20757. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20758. return this;
  20759. }
  20760. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20761. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20762. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20763. var position = BABYLON.Vector3.Zero();
  20764. var normal = BABYLON.Vector3.Zero();
  20765. var uv = BABYLON.Vector2.Zero();
  20766. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20767. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20768. for (var index = 0; index < positions.length; index += 3) {
  20769. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20770. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20771. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20772. // Compute height
  20773. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20774. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20775. var pos = (u + v * heightMapWidth) * 4;
  20776. var r = buffer[pos] / 255.0;
  20777. var g = buffer[pos + 1] / 255.0;
  20778. var b = buffer[pos + 2] / 255.0;
  20779. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20780. normal.normalize();
  20781. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20782. position = position.add(normal);
  20783. position.toArray(positions, index);
  20784. }
  20785. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20786. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20787. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20788. return this;
  20789. };
  20790. /**
  20791. * Modify the mesh to get a flat shading rendering.
  20792. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20793. * This method returns the Mesh.
  20794. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20795. */
  20796. Mesh.prototype.convertToFlatShadedMesh = function () {
  20797. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20798. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20799. var kinds = this.getVerticesDataKinds();
  20800. var vbs = [];
  20801. var data = [];
  20802. var newdata = [];
  20803. var updatableNormals = false;
  20804. var kindIndex;
  20805. var kind;
  20806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20807. kind = kinds[kindIndex];
  20808. var vertexBuffer = this.getVertexBuffer(kind);
  20809. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20810. updatableNormals = vertexBuffer.isUpdatable();
  20811. kinds.splice(kindIndex, 1);
  20812. kindIndex--;
  20813. continue;
  20814. }
  20815. vbs[kind] = vertexBuffer;
  20816. data[kind] = vbs[kind].getData();
  20817. newdata[kind] = [];
  20818. }
  20819. // Save previous submeshes
  20820. var previousSubmeshes = this.subMeshes.slice(0);
  20821. var indices = this.getIndices();
  20822. var totalIndices = this.getTotalIndices();
  20823. // Generating unique vertices per face
  20824. var index;
  20825. for (index = 0; index < totalIndices; index++) {
  20826. var vertexIndex = indices[index];
  20827. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20828. kind = kinds[kindIndex];
  20829. var stride = vbs[kind].getStrideSize();
  20830. for (var offset = 0; offset < stride; offset++) {
  20831. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20832. }
  20833. }
  20834. }
  20835. // Updating faces & normal
  20836. var normals = [];
  20837. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20838. for (index = 0; index < totalIndices; index += 3) {
  20839. indices[index] = index;
  20840. indices[index + 1] = index + 1;
  20841. indices[index + 2] = index + 2;
  20842. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20843. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20844. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20845. var p1p2 = p1.subtract(p2);
  20846. var p3p2 = p3.subtract(p2);
  20847. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20848. // Store same normals for every vertex
  20849. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20850. normals.push(normal.x);
  20851. normals.push(normal.y);
  20852. normals.push(normal.z);
  20853. }
  20854. }
  20855. this.setIndices(indices);
  20856. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20857. // Updating vertex buffers
  20858. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20859. kind = kinds[kindIndex];
  20860. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20861. }
  20862. // Updating submeshes
  20863. this.releaseSubMeshes();
  20864. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20865. var previousOne = previousSubmeshes[submeshIndex];
  20866. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20867. }
  20868. this.synchronizeInstances();
  20869. return this;
  20870. };
  20871. /**
  20872. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20873. * In other words, more vertices, no more indices and a single bigger VBO.
  20874. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20875. * Returns the Mesh.
  20876. */
  20877. Mesh.prototype.convertToUnIndexedMesh = function () {
  20878. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20879. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20880. var kinds = this.getVerticesDataKinds();
  20881. var vbs = [];
  20882. var data = [];
  20883. var newdata = [];
  20884. var updatableNormals = false;
  20885. var kindIndex;
  20886. var kind;
  20887. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20888. kind = kinds[kindIndex];
  20889. var vertexBuffer = this.getVertexBuffer(kind);
  20890. vbs[kind] = vertexBuffer;
  20891. data[kind] = vbs[kind].getData();
  20892. newdata[kind] = [];
  20893. }
  20894. // Save previous submeshes
  20895. var previousSubmeshes = this.subMeshes.slice(0);
  20896. var indices = this.getIndices();
  20897. var totalIndices = this.getTotalIndices();
  20898. // Generating unique vertices per face
  20899. var index;
  20900. for (index = 0; index < totalIndices; index++) {
  20901. var vertexIndex = indices[index];
  20902. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20903. kind = kinds[kindIndex];
  20904. var stride = vbs[kind].getStrideSize();
  20905. for (var offset = 0; offset < stride; offset++) {
  20906. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20907. }
  20908. }
  20909. }
  20910. // Updating indices
  20911. for (index = 0; index < totalIndices; index += 3) {
  20912. indices[index] = index;
  20913. indices[index + 1] = index + 1;
  20914. indices[index + 2] = index + 2;
  20915. }
  20916. this.setIndices(indices);
  20917. // Updating vertex buffers
  20918. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20919. kind = kinds[kindIndex];
  20920. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20921. }
  20922. // Updating submeshes
  20923. this.releaseSubMeshes();
  20924. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20925. var previousOne = previousSubmeshes[submeshIndex];
  20926. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20927. }
  20928. this._unIndexed = true;
  20929. this.synchronizeInstances();
  20930. return this;
  20931. };
  20932. /**
  20933. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20934. * This method returns the Mesh.
  20935. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20936. */
  20937. Mesh.prototype.flipFaces = function (flipNormals) {
  20938. if (flipNormals === void 0) { flipNormals = false; }
  20939. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20940. var i;
  20941. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20942. for (i = 0; i < vertex_data.normals.length; i++) {
  20943. vertex_data.normals[i] *= -1;
  20944. }
  20945. }
  20946. var temp;
  20947. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20948. // reassign indices
  20949. temp = vertex_data.indices[i + 1];
  20950. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20951. vertex_data.indices[i + 2] = temp;
  20952. }
  20953. vertex_data.applyToMesh(this);
  20954. return this;
  20955. };
  20956. // Instances
  20957. /**
  20958. * Creates a new InstancedMesh object from the mesh model.
  20959. * An instance shares the same properties and the same material than its model.
  20960. * Only these properties of each instance can then be set individually :
  20961. * - position
  20962. * - rotation
  20963. * - rotationQuaternion
  20964. * - setPivotMatrix
  20965. * - scaling
  20966. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20967. * Warning : this method is not supported for Line mesh and LineSystem
  20968. */
  20969. Mesh.prototype.createInstance = function (name) {
  20970. return new BABYLON.InstancedMesh(name, this);
  20971. };
  20972. /**
  20973. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20974. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20975. * This method returns the Mesh.
  20976. */
  20977. Mesh.prototype.synchronizeInstances = function () {
  20978. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20979. var instance = this.instances[instanceIndex];
  20980. instance._syncSubMeshes();
  20981. }
  20982. return this;
  20983. };
  20984. /**
  20985. * Simplify the mesh according to the given array of settings.
  20986. * Function will return immediately and will simplify async. It returns the Mesh.
  20987. * @param settings a collection of simplification settings.
  20988. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20989. * @param type the type of simplification to run.
  20990. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20991. */
  20992. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20993. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20994. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20995. this.getScene().simplificationQueue.addTask({
  20996. settings: settings,
  20997. parallelProcessing: parallelProcessing,
  20998. mesh: this,
  20999. simplificationType: simplificationType,
  21000. successCallback: successCallback
  21001. });
  21002. return this;
  21003. };
  21004. /**
  21005. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21006. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21007. * This should be used together with the simplification to avoid disappearing triangles.
  21008. * Returns the Mesh.
  21009. * @param successCallback an optional success callback to be called after the optimization finished.
  21010. */
  21011. Mesh.prototype.optimizeIndices = function (successCallback) {
  21012. var _this = this;
  21013. var indices = this.getIndices();
  21014. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21015. var vectorPositions = [];
  21016. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21017. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21018. }
  21019. var dupes = [];
  21020. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21021. var realPos = vectorPositions.length - 1 - iteration;
  21022. var testedPosition = vectorPositions[realPos];
  21023. for (var j = 0; j < realPos; ++j) {
  21024. var againstPosition = vectorPositions[j];
  21025. if (testedPosition.equals(againstPosition)) {
  21026. dupes[realPos] = j;
  21027. break;
  21028. }
  21029. }
  21030. }, function () {
  21031. for (var i = 0; i < indices.length; ++i) {
  21032. indices[i] = dupes[indices[i]] || indices[i];
  21033. }
  21034. //indices are now reordered
  21035. var originalSubMeshes = _this.subMeshes.slice(0);
  21036. _this.setIndices(indices);
  21037. _this.subMeshes = originalSubMeshes;
  21038. if (successCallback) {
  21039. successCallback(_this);
  21040. }
  21041. });
  21042. return this;
  21043. };
  21044. Mesh.prototype.serialize = function (serializationObject) {
  21045. serializationObject.name = this.name;
  21046. serializationObject.id = this.id;
  21047. serializationObject.type = this.getClassName();
  21048. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21049. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21050. }
  21051. serializationObject.position = this.position.asArray();
  21052. if (this.rotationQuaternion) {
  21053. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21054. }
  21055. else if (this.rotation) {
  21056. serializationObject.rotation = this.rotation.asArray();
  21057. }
  21058. serializationObject.scaling = this.scaling.asArray();
  21059. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21060. serializationObject.isEnabled = this.isEnabled();
  21061. serializationObject.isVisible = this.isVisible;
  21062. serializationObject.infiniteDistance = this.infiniteDistance;
  21063. serializationObject.pickable = this.isPickable;
  21064. serializationObject.receiveShadows = this.receiveShadows;
  21065. serializationObject.billboardMode = this.billboardMode;
  21066. serializationObject.visibility = this.visibility;
  21067. serializationObject.checkCollisions = this.checkCollisions;
  21068. serializationObject.isBlocker = this.isBlocker;
  21069. // Parent
  21070. if (this.parent) {
  21071. serializationObject.parentId = this.parent.id;
  21072. }
  21073. // Geometry
  21074. var geometry = this._geometry;
  21075. if (geometry) {
  21076. var geometryId = geometry.id;
  21077. serializationObject.geometryId = geometryId;
  21078. // SubMeshes
  21079. serializationObject.subMeshes = [];
  21080. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21081. var subMesh = this.subMeshes[subIndex];
  21082. serializationObject.subMeshes.push({
  21083. materialIndex: subMesh.materialIndex,
  21084. verticesStart: subMesh.verticesStart,
  21085. verticesCount: subMesh.verticesCount,
  21086. indexStart: subMesh.indexStart,
  21087. indexCount: subMesh.indexCount
  21088. });
  21089. }
  21090. }
  21091. // Material
  21092. if (this.material) {
  21093. serializationObject.materialId = this.material.id;
  21094. }
  21095. else {
  21096. this.material = null;
  21097. }
  21098. // Morph targets
  21099. if (this.morphTargetManager) {
  21100. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21101. }
  21102. // Skeleton
  21103. if (this.skeleton) {
  21104. serializationObject.skeletonId = this.skeleton.id;
  21105. }
  21106. // Physics
  21107. //TODO implement correct serialization for physics impostors.
  21108. if (this.getPhysicsImpostor()) {
  21109. var impostor = this.getPhysicsImpostor();
  21110. serializationObject.physicsMass = impostor.getParam("mass");
  21111. serializationObject.physicsFriction = impostor.getParam("friction");
  21112. serializationObject.physicsRestitution = impostor.getParam("mass");
  21113. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21114. }
  21115. // Metadata
  21116. if (this.metadata) {
  21117. serializationObject.metadata = this.metadata;
  21118. }
  21119. // Instances
  21120. serializationObject.instances = [];
  21121. for (var index = 0; index < this.instances.length; index++) {
  21122. var instance = this.instances[index];
  21123. var serializationInstance = {
  21124. name: instance.name,
  21125. position: instance.position.asArray(),
  21126. scaling: instance.scaling.asArray()
  21127. };
  21128. if (instance.rotationQuaternion) {
  21129. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21130. }
  21131. else if (instance.rotation) {
  21132. serializationInstance.rotation = instance.rotation.asArray();
  21133. }
  21134. serializationObject.instances.push(serializationInstance);
  21135. // Animations
  21136. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21137. serializationInstance.ranges = instance.serializeAnimationRanges();
  21138. }
  21139. //
  21140. // Animations
  21141. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21142. serializationObject.ranges = this.serializeAnimationRanges();
  21143. // Layer mask
  21144. serializationObject.layerMask = this.layerMask;
  21145. // Alpha
  21146. serializationObject.alphaIndex = this.alphaIndex;
  21147. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21148. // Overlay
  21149. serializationObject.overlayAlpha = this.overlayAlpha;
  21150. serializationObject.overlayColor = this.overlayColor.asArray();
  21151. serializationObject.renderOverlay = this.renderOverlay;
  21152. // Fog
  21153. serializationObject.applyFog = this.applyFog;
  21154. // Action Manager
  21155. if (this.actionManager) {
  21156. serializationObject.actions = this.actionManager.serialize(this.name);
  21157. }
  21158. };
  21159. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21160. if (!this.geometry) {
  21161. return;
  21162. }
  21163. this._markSubMeshesAsAttributesDirty();
  21164. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21165. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21166. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21167. this.morphTargetManager = undefined;
  21168. return;
  21169. }
  21170. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21171. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21172. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21173. if (morphTarget.hasNormals) {
  21174. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21175. }
  21176. if (morphTarget.hasTangents) {
  21177. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21178. }
  21179. }
  21180. }
  21181. else {
  21182. var index = 0;
  21183. // Positions
  21184. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21185. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21186. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21187. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21188. }
  21189. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21190. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21191. }
  21192. index++;
  21193. }
  21194. }
  21195. };
  21196. // Statics
  21197. /**
  21198. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21199. * The parameter `parsedMesh` is the mesh to be copied.
  21200. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21201. */
  21202. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21203. var mesh;
  21204. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21205. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21206. }
  21207. else {
  21208. mesh = new Mesh(parsedMesh.name, scene);
  21209. }
  21210. mesh.id = parsedMesh.id;
  21211. if (BABYLON.Tags) {
  21212. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21213. }
  21214. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21215. if (parsedMesh.metadata !== undefined) {
  21216. mesh.metadata = parsedMesh.metadata;
  21217. }
  21218. if (parsedMesh.rotationQuaternion) {
  21219. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21220. }
  21221. else if (parsedMesh.rotation) {
  21222. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21223. }
  21224. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21225. if (parsedMesh.localMatrix) {
  21226. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21227. }
  21228. else if (parsedMesh.pivotMatrix) {
  21229. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21230. }
  21231. mesh.setEnabled(parsedMesh.isEnabled);
  21232. mesh.isVisible = parsedMesh.isVisible;
  21233. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21234. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21235. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21236. if (parsedMesh.applyFog !== undefined) {
  21237. mesh.applyFog = parsedMesh.applyFog;
  21238. }
  21239. if (parsedMesh.pickable !== undefined) {
  21240. mesh.isPickable = parsedMesh.pickable;
  21241. }
  21242. if (parsedMesh.alphaIndex !== undefined) {
  21243. mesh.alphaIndex = parsedMesh.alphaIndex;
  21244. }
  21245. mesh.receiveShadows = parsedMesh.receiveShadows;
  21246. mesh.billboardMode = parsedMesh.billboardMode;
  21247. if (parsedMesh.visibility !== undefined) {
  21248. mesh.visibility = parsedMesh.visibility;
  21249. }
  21250. mesh.checkCollisions = parsedMesh.checkCollisions;
  21251. if (parsedMesh.isBlocker !== undefined) {
  21252. mesh.isBlocker = parsedMesh.isBlocker;
  21253. }
  21254. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21255. // freezeWorldMatrix
  21256. if (parsedMesh.freezeWorldMatrix) {
  21257. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21258. }
  21259. // Parent
  21260. if (parsedMesh.parentId) {
  21261. mesh._waitingParentId = parsedMesh.parentId;
  21262. }
  21263. // Actions
  21264. if (parsedMesh.actions !== undefined) {
  21265. mesh._waitingActions = parsedMesh.actions;
  21266. }
  21267. // Overlay
  21268. if (parsedMesh.overlayAlpha !== undefined) {
  21269. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21270. }
  21271. if (parsedMesh.overlayColor !== undefined) {
  21272. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21273. }
  21274. if (parsedMesh.renderOverlay !== undefined) {
  21275. mesh.renderOverlay = parsedMesh.renderOverlay;
  21276. }
  21277. // Geometry
  21278. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21279. if (parsedMesh.delayLoadingFile) {
  21280. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21281. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21282. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21283. if (parsedMesh._binaryInfo) {
  21284. mesh._binaryInfo = parsedMesh._binaryInfo;
  21285. }
  21286. mesh._delayInfo = [];
  21287. if (parsedMesh.hasUVs) {
  21288. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21289. }
  21290. if (parsedMesh.hasUVs2) {
  21291. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21292. }
  21293. if (parsedMesh.hasUVs3) {
  21294. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21295. }
  21296. if (parsedMesh.hasUVs4) {
  21297. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21298. }
  21299. if (parsedMesh.hasUVs5) {
  21300. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21301. }
  21302. if (parsedMesh.hasUVs6) {
  21303. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21304. }
  21305. if (parsedMesh.hasColors) {
  21306. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21307. }
  21308. if (parsedMesh.hasMatricesIndices) {
  21309. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21310. }
  21311. if (parsedMesh.hasMatricesWeights) {
  21312. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21313. }
  21314. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21315. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21316. mesh._checkDelayState();
  21317. }
  21318. }
  21319. else {
  21320. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21321. }
  21322. // Material
  21323. if (parsedMesh.materialId) {
  21324. mesh.setMaterialByID(parsedMesh.materialId);
  21325. }
  21326. else {
  21327. mesh.material = null;
  21328. }
  21329. // Morph targets
  21330. if (parsedMesh.morphTargetManagerId > -1) {
  21331. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21332. }
  21333. // Skeleton
  21334. if (parsedMesh.skeletonId > -1) {
  21335. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21336. if (parsedMesh.numBoneInfluencers) {
  21337. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21338. }
  21339. }
  21340. // Animations
  21341. if (parsedMesh.animations) {
  21342. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21343. var parsedAnimation = parsedMesh.animations[animationIndex];
  21344. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21345. }
  21346. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21347. }
  21348. if (parsedMesh.autoAnimate) {
  21349. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21350. }
  21351. // Layer Mask
  21352. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21353. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21354. }
  21355. else {
  21356. mesh.layerMask = 0x0FFFFFFF;
  21357. }
  21358. // Physics
  21359. if (parsedMesh.physicsImpostor) {
  21360. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21361. mass: parsedMesh.physicsMass,
  21362. friction: parsedMesh.physicsFriction,
  21363. restitution: parsedMesh.physicsRestitution
  21364. }, scene);
  21365. }
  21366. // Instances
  21367. if (parsedMesh.instances) {
  21368. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21369. var parsedInstance = parsedMesh.instances[index];
  21370. var instance = mesh.createInstance(parsedInstance.name);
  21371. if (BABYLON.Tags) {
  21372. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21373. }
  21374. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21375. if (parsedInstance.parentId) {
  21376. instance._waitingParentId = parsedInstance.parentId;
  21377. }
  21378. if (parsedInstance.rotationQuaternion) {
  21379. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21380. }
  21381. else if (parsedInstance.rotation) {
  21382. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21383. }
  21384. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21385. instance.checkCollisions = mesh.checkCollisions;
  21386. if (parsedMesh.animations) {
  21387. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21388. parsedAnimation = parsedMesh.animations[animationIndex];
  21389. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21390. }
  21391. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21392. }
  21393. }
  21394. }
  21395. return mesh;
  21396. };
  21397. /**
  21398. * Creates a ribbon mesh.
  21399. * Please consider using the same method from the MeshBuilder class instead.
  21400. * 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.
  21401. *
  21402. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21403. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21404. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21405. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21406. * 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.
  21407. * 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.
  21408. * 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
  21409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21412. */
  21413. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21414. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21415. pathArray: pathArray,
  21416. closeArray: closeArray,
  21417. closePath: closePath,
  21418. offset: offset,
  21419. updatable: updatable,
  21420. sideOrientation: sideOrientation,
  21421. instance: instance
  21422. }, scene);
  21423. };
  21424. /**
  21425. * Creates a plane polygonal mesh. By default, this is a disc.
  21426. * Please consider using the same method from the MeshBuilder class instead.
  21427. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21428. * 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.
  21429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21432. */
  21433. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21434. var options = {
  21435. radius: radius,
  21436. tessellation: tessellation,
  21437. sideOrientation: sideOrientation,
  21438. updatable: updatable
  21439. };
  21440. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21441. };
  21442. /**
  21443. * Creates a box mesh.
  21444. * Please consider using the same method from the MeshBuilder class instead.
  21445. * The parameter `size` sets the size (float) of each box side (default 1).
  21446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21447. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21449. */
  21450. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21451. var options = {
  21452. size: size,
  21453. sideOrientation: sideOrientation,
  21454. updatable: updatable
  21455. };
  21456. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21457. };
  21458. /**
  21459. * Creates a sphere mesh.
  21460. * Please consider using the same method from the MeshBuilder class instead.
  21461. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21462. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21464. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21466. */
  21467. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21468. var options = {
  21469. segments: segments,
  21470. diameterX: diameter,
  21471. diameterY: diameter,
  21472. diameterZ: diameter,
  21473. sideOrientation: sideOrientation,
  21474. updatable: updatable
  21475. };
  21476. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21477. };
  21478. /**
  21479. * Creates a cylinder or a cone mesh.
  21480. * Please consider using the same method from the MeshBuilder class instead.
  21481. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21482. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21483. * 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.
  21484. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21485. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21489. */
  21490. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21491. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21492. if (scene !== undefined) {
  21493. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21494. updatable = scene;
  21495. }
  21496. scene = subdivisions;
  21497. subdivisions = 1;
  21498. }
  21499. var options = {
  21500. height: height,
  21501. diameterTop: diameterTop,
  21502. diameterBottom: diameterBottom,
  21503. tessellation: tessellation,
  21504. subdivisions: subdivisions,
  21505. sideOrientation: sideOrientation,
  21506. updatable: updatable
  21507. };
  21508. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21509. };
  21510. // Torus (Code from SharpDX.org)
  21511. /**
  21512. * Creates a torus mesh.
  21513. * Please consider using the same method from the MeshBuilder class instead.
  21514. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21515. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21516. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21520. */
  21521. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21522. var options = {
  21523. diameter: diameter,
  21524. thickness: thickness,
  21525. tessellation: tessellation,
  21526. sideOrientation: sideOrientation,
  21527. updatable: updatable
  21528. };
  21529. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21530. };
  21531. /**
  21532. * Creates a torus knot mesh.
  21533. * Please consider using the same method from the MeshBuilder class instead.
  21534. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21535. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21536. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21537. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21541. */
  21542. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21543. var options = {
  21544. radius: radius,
  21545. tube: tube,
  21546. radialSegments: radialSegments,
  21547. tubularSegments: tubularSegments,
  21548. p: p,
  21549. q: q,
  21550. sideOrientation: sideOrientation,
  21551. updatable: updatable
  21552. };
  21553. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21554. };
  21555. /**
  21556. * Creates a line mesh.
  21557. * Please consider using the same method from the MeshBuilder class instead.
  21558. * 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.
  21559. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21560. * The parameter `points` is an array successive Vector3.
  21561. * 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
  21562. * When updating an instance, remember that only point positions can change, not the number of points.
  21563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21564. */
  21565. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21566. var options = {
  21567. points: points,
  21568. updatable: updatable,
  21569. instance: instance
  21570. };
  21571. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21572. };
  21573. /**
  21574. * Creates a dashed line mesh.
  21575. * Please consider using the same method from the MeshBuilder class instead.
  21576. * 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.
  21577. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21578. * The parameter `points` is an array successive Vector3.
  21579. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21580. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21581. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21582. * 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
  21583. * When updating an instance, remember that only point positions can change, not the number of points.
  21584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21585. */
  21586. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21587. var options = {
  21588. points: points,
  21589. dashSize: dashSize,
  21590. gapSize: gapSize,
  21591. dashNb: dashNb,
  21592. updatable: updatable,
  21593. instance: instance
  21594. };
  21595. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21596. };
  21597. /**
  21598. * Creates a polygon mesh.
  21599. * Please consider using the same method from the MeshBuilder class instead.
  21600. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21601. * 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.
  21602. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21603. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21604. * Remember you can only change the shape positions, not their number when updating a polygon.
  21605. */
  21606. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21607. var options = {
  21608. shape: shape,
  21609. holes: holes,
  21610. updatable: updatable,
  21611. sideOrientation: sideOrientation
  21612. };
  21613. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21614. };
  21615. /**
  21616. * Creates an extruded polygon mesh, with depth in the Y direction.
  21617. * Please consider using the same method from the MeshBuilder class instead.
  21618. */
  21619. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21620. var options = {
  21621. shape: shape,
  21622. holes: holes,
  21623. depth: depth,
  21624. updatable: updatable,
  21625. sideOrientation: sideOrientation
  21626. };
  21627. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21628. };
  21629. /**
  21630. * Creates an extruded shape mesh.
  21631. * 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.
  21632. * Please consider using the same method from the MeshBuilder class instead.
  21633. *
  21634. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21635. * 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
  21636. * extruded along the Z axis.
  21637. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21638. * 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.
  21639. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21640. * 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
  21641. * 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
  21642. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21646. */
  21647. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21648. var options = {
  21649. shape: shape,
  21650. path: path,
  21651. scale: scale,
  21652. rotation: rotation,
  21653. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21654. sideOrientation: sideOrientation,
  21655. instance: instance,
  21656. updatable: updatable
  21657. };
  21658. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21659. };
  21660. /**
  21661. * Creates an custom extruded shape mesh.
  21662. * 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.
  21663. * Please consider using the same method from the MeshBuilder class instead.
  21664. *
  21665. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21666. * 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
  21667. * extruded along the Z axis.
  21668. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21669. * 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
  21670. * and the distance of this point from the begining of the path :
  21671. * ```javascript
  21672. * var rotationFunction = function(i, distance) {
  21673. * // do things
  21674. * return rotationValue; }
  21675. * ```
  21676. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21677. * 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
  21678. * and the distance of this point from the begining of the path :
  21679. * ```javascript
  21680. * var scaleFunction = function(i, distance) {
  21681. * // do things
  21682. * return scaleValue;}
  21683. * ```
  21684. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21685. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21686. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21687. * 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
  21688. * 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
  21689. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21693. */
  21694. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21695. var options = {
  21696. shape: shape,
  21697. path: path,
  21698. scaleFunction: scaleFunction,
  21699. rotationFunction: rotationFunction,
  21700. ribbonCloseArray: ribbonCloseArray,
  21701. ribbonClosePath: ribbonClosePath,
  21702. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21703. sideOrientation: sideOrientation,
  21704. instance: instance,
  21705. updatable: updatable
  21706. };
  21707. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21708. };
  21709. /**
  21710. * Creates lathe mesh.
  21711. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21712. * Please consider using the same method from the MeshBuilder class instead.
  21713. * 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
  21714. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21715. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21716. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21717. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21718. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21720. */
  21721. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21722. var options = {
  21723. shape: shape,
  21724. radius: radius,
  21725. tessellation: tessellation,
  21726. sideOrientation: sideOrientation,
  21727. updatable: updatable
  21728. };
  21729. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21730. };
  21731. /**
  21732. * Creates a plane mesh.
  21733. * Please consider using the same method from the MeshBuilder class instead.
  21734. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21737. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21738. */
  21739. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21740. var options = {
  21741. size: size,
  21742. width: size,
  21743. height: size,
  21744. sideOrientation: sideOrientation,
  21745. updatable: updatable
  21746. };
  21747. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21748. };
  21749. /**
  21750. * Creates a ground mesh.
  21751. * Please consider using the same method from the MeshBuilder class instead.
  21752. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21753. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21754. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21755. */
  21756. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21757. var options = {
  21758. width: width,
  21759. height: height,
  21760. subdivisions: subdivisions,
  21761. updatable: updatable
  21762. };
  21763. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21764. };
  21765. /**
  21766. * Creates a tiled ground mesh.
  21767. * Please consider using the same method from the MeshBuilder class instead.
  21768. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21769. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21770. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21771. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21772. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21773. * numbers of subdivisions on the ground width and height of each tile.
  21774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21775. */
  21776. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21777. var options = {
  21778. xmin: xmin,
  21779. zmin: zmin,
  21780. xmax: xmax,
  21781. zmax: zmax,
  21782. subdivisions: subdivisions,
  21783. precision: precision,
  21784. updatable: updatable
  21785. };
  21786. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21787. };
  21788. /**
  21789. * Creates a ground mesh from a height map.
  21790. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21791. * Please consider using the same method from the MeshBuilder class instead.
  21792. * The parameter `url` sets the URL of the height map image resource.
  21793. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21794. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21795. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21796. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21797. * 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).
  21798. * This function is passed the newly built mesh :
  21799. * ```javascript
  21800. * function(mesh) { // do things
  21801. * return; }
  21802. * ```
  21803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21804. */
  21805. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21806. var options = {
  21807. width: width,
  21808. height: height,
  21809. subdivisions: subdivisions,
  21810. minHeight: minHeight,
  21811. maxHeight: maxHeight,
  21812. updatable: updatable,
  21813. onReady: onReady
  21814. };
  21815. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21816. };
  21817. /**
  21818. * Creates a tube mesh.
  21819. * 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.
  21820. * Please consider using the same method from the MeshBuilder class instead.
  21821. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21822. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21823. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21824. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21825. * 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.
  21826. * It must return a radius value (positive float) :
  21827. * ```javascript
  21828. * var radiusFunction = function(i, distance) {
  21829. * // do things
  21830. * return radius; }
  21831. * ```
  21832. * 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
  21833. * 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
  21834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21835. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21836. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21837. */
  21838. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21839. var options = {
  21840. path: path,
  21841. radius: radius,
  21842. tessellation: tessellation,
  21843. radiusFunction: radiusFunction,
  21844. arc: 1,
  21845. cap: cap,
  21846. updatable: updatable,
  21847. sideOrientation: sideOrientation,
  21848. instance: instance
  21849. };
  21850. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21851. };
  21852. /**
  21853. * Creates a polyhedron mesh.
  21854. * Please consider using the same method from the MeshBuilder class instead.
  21855. * 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
  21856. * to choose the wanted type.
  21857. * The parameter `size` (positive float, default 1) sets the polygon size.
  21858. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21859. * 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`.
  21860. * 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
  21861. * 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)`).
  21862. * 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
  21863. * 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.
  21864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21867. */
  21868. Mesh.CreatePolyhedron = function (name, options, scene) {
  21869. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21870. };
  21871. /**
  21872. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21873. * Please consider using the same method from the MeshBuilder class instead.
  21874. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21875. * 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`).
  21876. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21877. * 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.
  21878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21879. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21880. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21881. */
  21882. Mesh.CreateIcoSphere = function (name, options, scene) {
  21883. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21884. };
  21885. /**
  21886. * Creates a decal mesh.
  21887. * Please consider using the same method from the MeshBuilder class instead.
  21888. * 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.
  21889. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21890. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21891. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21892. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21893. */
  21894. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21895. var options = {
  21896. position: position,
  21897. normal: normal,
  21898. size: size,
  21899. angle: angle
  21900. };
  21901. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21902. };
  21903. // Skeletons
  21904. /**
  21905. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21906. */
  21907. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21908. var source;
  21909. if (!this._sourcePositions) {
  21910. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21911. this._sourcePositions = new Float32Array(source);
  21912. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21913. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21914. }
  21915. }
  21916. return this._sourcePositions;
  21917. };
  21918. /**
  21919. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21920. */
  21921. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21922. var source;
  21923. if (!this._sourceNormals) {
  21924. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21925. this._sourceNormals = new Float32Array(source);
  21926. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21927. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21928. }
  21929. }
  21930. return this._sourceNormals;
  21931. };
  21932. /**
  21933. * Updates the vertex buffer by applying transformation from the bones.
  21934. * Returns the Mesh.
  21935. *
  21936. * @param {skeleton} skeleton to apply
  21937. */
  21938. Mesh.prototype.applySkeleton = function (skeleton) {
  21939. if (!this.geometry) {
  21940. return this;
  21941. }
  21942. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21943. return this;
  21944. }
  21945. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21946. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21947. return this;
  21948. }
  21949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21950. return this;
  21951. }
  21952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21953. return this;
  21954. }
  21955. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21956. return this;
  21957. }
  21958. if (!this._sourcePositions) {
  21959. var submeshes = this.subMeshes.slice();
  21960. this.setPositionsForCPUSkinning();
  21961. this.subMeshes = submeshes;
  21962. }
  21963. if (!this._sourceNormals) {
  21964. this.setNormalsForCPUSkinning();
  21965. }
  21966. // positionsData checks for not being Float32Array will only pass at most once
  21967. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21968. if (!(positionsData instanceof Float32Array)) {
  21969. positionsData = new Float32Array(positionsData);
  21970. }
  21971. // normalsData checks for not being Float32Array will only pass at most once
  21972. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21973. if (!(normalsData instanceof Float32Array)) {
  21974. normalsData = new Float32Array(normalsData);
  21975. }
  21976. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21977. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21978. var needExtras = this.numBoneInfluencers > 4;
  21979. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21980. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21981. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21982. var tempVector3 = BABYLON.Vector3.Zero();
  21983. var finalMatrix = new BABYLON.Matrix();
  21984. var tempMatrix = new BABYLON.Matrix();
  21985. var matWeightIdx = 0;
  21986. var inf;
  21987. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21988. var weight;
  21989. for (inf = 0; inf < 4; inf++) {
  21990. weight = matricesWeightsData[matWeightIdx + inf];
  21991. if (weight > 0) {
  21992. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21993. finalMatrix.addToSelf(tempMatrix);
  21994. }
  21995. else
  21996. break;
  21997. }
  21998. if (needExtras) {
  21999. for (inf = 0; inf < 4; inf++) {
  22000. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22001. if (weight > 0) {
  22002. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22003. finalMatrix.addToSelf(tempMatrix);
  22004. }
  22005. else
  22006. break;
  22007. }
  22008. }
  22009. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22010. tempVector3.toArray(positionsData, index);
  22011. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22012. tempVector3.toArray(normalsData, index);
  22013. finalMatrix.reset();
  22014. }
  22015. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22016. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22017. return this;
  22018. };
  22019. // Tools
  22020. /**
  22021. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22022. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22023. */
  22024. Mesh.MinMax = function (meshes) {
  22025. var minVector = null;
  22026. var maxVector = null;
  22027. meshes.forEach(function (mesh, index, array) {
  22028. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22029. if (!minVector) {
  22030. minVector = boundingBox.minimumWorld;
  22031. maxVector = boundingBox.maximumWorld;
  22032. }
  22033. else {
  22034. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22035. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22036. }
  22037. });
  22038. return {
  22039. min: minVector,
  22040. max: maxVector
  22041. };
  22042. };
  22043. /**
  22044. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22045. */
  22046. Mesh.Center = function (meshesOrMinMaxVector) {
  22047. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22048. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22049. };
  22050. /**
  22051. * Merge the array of meshes into a single mesh for performance reasons.
  22052. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22053. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22054. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22055. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22056. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22057. */
  22058. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22059. if (disposeSource === void 0) { disposeSource = true; }
  22060. var index;
  22061. if (!allow32BitsIndices) {
  22062. var totalVertices = 0;
  22063. // Counting vertices
  22064. for (index = 0; index < meshes.length; index++) {
  22065. if (meshes[index]) {
  22066. totalVertices += meshes[index].getTotalVertices();
  22067. if (totalVertices > 65536) {
  22068. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22069. return null;
  22070. }
  22071. }
  22072. }
  22073. }
  22074. // Merge
  22075. var vertexData;
  22076. var otherVertexData;
  22077. var indiceArray = new Array();
  22078. var source;
  22079. for (index = 0; index < meshes.length; index++) {
  22080. if (meshes[index]) {
  22081. meshes[index].computeWorldMatrix(true);
  22082. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22083. otherVertexData.transform(meshes[index].getWorldMatrix());
  22084. if (vertexData) {
  22085. vertexData.merge(otherVertexData);
  22086. }
  22087. else {
  22088. vertexData = otherVertexData;
  22089. source = meshes[index];
  22090. }
  22091. if (subdivideWithSubMeshes) {
  22092. indiceArray.push(meshes[index].getTotalIndices());
  22093. }
  22094. }
  22095. }
  22096. if (!meshSubclass) {
  22097. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22098. }
  22099. vertexData.applyToMesh(meshSubclass);
  22100. // Setting properties
  22101. meshSubclass.material = source.material;
  22102. meshSubclass.checkCollisions = source.checkCollisions;
  22103. // Cleaning
  22104. if (disposeSource) {
  22105. for (index = 0; index < meshes.length; index++) {
  22106. if (meshes[index]) {
  22107. meshes[index].dispose();
  22108. }
  22109. }
  22110. }
  22111. // Subdivide
  22112. if (subdivideWithSubMeshes) {
  22113. //-- Suppresions du submesh global
  22114. meshSubclass.releaseSubMeshes();
  22115. index = 0;
  22116. var offset = 0;
  22117. //-- aplique la subdivision en fonction du tableau d'indices
  22118. while (index < indiceArray.length) {
  22119. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22120. offset += indiceArray[index];
  22121. index++;
  22122. }
  22123. }
  22124. return meshSubclass;
  22125. };
  22126. return Mesh;
  22127. }(BABYLON.AbstractMesh));
  22128. // Consts
  22129. Mesh._FRONTSIDE = 0;
  22130. Mesh._BACKSIDE = 1;
  22131. Mesh._DOUBLESIDE = 2;
  22132. Mesh._DEFAULTSIDE = 0;
  22133. Mesh._NO_CAP = 0;
  22134. Mesh._CAP_START = 1;
  22135. Mesh._CAP_END = 2;
  22136. Mesh._CAP_ALL = 3;
  22137. BABYLON.Mesh = Mesh;
  22138. })(BABYLON || (BABYLON = {}));
  22139. //# sourceMappingURL=babylon.mesh.js.map
  22140. var BABYLON;
  22141. (function (BABYLON) {
  22142. var BaseSubMesh = (function () {
  22143. function BaseSubMesh() {
  22144. }
  22145. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22146. get: function () {
  22147. return this._materialEffect;
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22153. if (this._materialEffect === effect) {
  22154. return;
  22155. }
  22156. this._materialDefines = defines;
  22157. this._materialEffect = effect;
  22158. };
  22159. return BaseSubMesh;
  22160. }());
  22161. BABYLON.BaseSubMesh = BaseSubMesh;
  22162. var SubMesh = (function (_super) {
  22163. __extends(SubMesh, _super);
  22164. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22165. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22166. var _this = _super.call(this) || this;
  22167. _this.materialIndex = materialIndex;
  22168. _this.verticesStart = verticesStart;
  22169. _this.verticesCount = verticesCount;
  22170. _this.indexStart = indexStart;
  22171. _this.indexCount = indexCount;
  22172. _this._renderId = 0;
  22173. _this._mesh = mesh;
  22174. _this._renderingMesh = renderingMesh || mesh;
  22175. mesh.subMeshes.push(_this);
  22176. _this._trianglePlanes = [];
  22177. _this._id = mesh.subMeshes.length - 1;
  22178. if (createBoundingBox) {
  22179. _this.refreshBoundingInfo();
  22180. mesh.computeWorldMatrix(true);
  22181. }
  22182. return _this;
  22183. }
  22184. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22185. get: function () {
  22186. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. /**
  22192. * Returns the submesh BoudingInfo object.
  22193. */
  22194. SubMesh.prototype.getBoundingInfo = function () {
  22195. if (this.IsGlobal) {
  22196. return this._mesh.getBoundingInfo();
  22197. }
  22198. return this._boundingInfo;
  22199. };
  22200. /**
  22201. * Sets the submesh BoundingInfo.
  22202. * Return the SubMesh.
  22203. */
  22204. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22205. this._boundingInfo = boundingInfo;
  22206. return this;
  22207. };
  22208. /**
  22209. * Returns the mesh of the current submesh.
  22210. */
  22211. SubMesh.prototype.getMesh = function () {
  22212. return this._mesh;
  22213. };
  22214. /**
  22215. * Returns the rendering mesh of the submesh.
  22216. */
  22217. SubMesh.prototype.getRenderingMesh = function () {
  22218. return this._renderingMesh;
  22219. };
  22220. /**
  22221. * Returns the submesh material.
  22222. */
  22223. SubMesh.prototype.getMaterial = function () {
  22224. var rootMaterial = this._renderingMesh.material;
  22225. if (rootMaterial && rootMaterial.getSubMaterial) {
  22226. var multiMaterial = rootMaterial;
  22227. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22228. if (this._currentMaterial !== effectiveMaterial) {
  22229. this._currentMaterial = effectiveMaterial;
  22230. if (this._materialDefines) {
  22231. this._materialDefines.markAllAsDirty();
  22232. }
  22233. }
  22234. return effectiveMaterial;
  22235. }
  22236. if (!rootMaterial) {
  22237. return this._mesh.getScene().defaultMaterial;
  22238. }
  22239. return rootMaterial;
  22240. };
  22241. // Methods
  22242. /**
  22243. * Sets a new updated BoundingInfo object to the submesh.
  22244. * Returns the SubMesh.
  22245. */
  22246. SubMesh.prototype.refreshBoundingInfo = function () {
  22247. this._lastColliderWorldVertices = null;
  22248. if (this.IsGlobal) {
  22249. return;
  22250. }
  22251. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22252. if (!data) {
  22253. this._boundingInfo = this._mesh._boundingInfo;
  22254. return;
  22255. }
  22256. var indices = this._renderingMesh.getIndices();
  22257. var extend;
  22258. //is this the only submesh?
  22259. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22260. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22261. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22262. }
  22263. else {
  22264. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22265. }
  22266. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22267. return this;
  22268. };
  22269. SubMesh.prototype._checkCollision = function (collider) {
  22270. return this.getBoundingInfo()._checkCollision(collider);
  22271. };
  22272. /**
  22273. * Updates the submesh BoundingInfo.
  22274. * Returns the Submesh.
  22275. */
  22276. SubMesh.prototype.updateBoundingInfo = function (world) {
  22277. if (!this.getBoundingInfo()) {
  22278. this.refreshBoundingInfo();
  22279. }
  22280. this.getBoundingInfo().update(world);
  22281. return this;
  22282. };
  22283. /**
  22284. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22285. * Boolean returned.
  22286. */
  22287. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22288. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22289. };
  22290. /**
  22291. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22292. * Boolean returned.
  22293. */
  22294. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22295. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22296. };
  22297. /**
  22298. * Renders the submesh.
  22299. * Returns it.
  22300. */
  22301. SubMesh.prototype.render = function (enableAlphaMode) {
  22302. this._renderingMesh.render(this, enableAlphaMode);
  22303. return this;
  22304. };
  22305. /**
  22306. * Returns a new Index Buffer.
  22307. * Type returned : WebGLBuffer.
  22308. */
  22309. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22310. if (!this._linesIndexBuffer) {
  22311. var linesIndices = [];
  22312. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22313. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22314. }
  22315. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22316. this.linesIndexCount = linesIndices.length;
  22317. }
  22318. return this._linesIndexBuffer;
  22319. };
  22320. /**
  22321. * True is the passed Ray intersects the submesh bounding box.
  22322. * Boolean returned.
  22323. */
  22324. SubMesh.prototype.canIntersects = function (ray) {
  22325. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22326. };
  22327. /**
  22328. * Returns an object IntersectionInfo.
  22329. */
  22330. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22331. var intersectInfo = null;
  22332. // LineMesh first as it's also a Mesh...
  22333. if (this._mesh instanceof BABYLON.LinesMesh) {
  22334. var lineMesh = this._mesh;
  22335. // Line test
  22336. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22337. var p0 = positions[indices[index]];
  22338. var p1 = positions[indices[index + 1]];
  22339. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22340. if (length < 0) {
  22341. continue;
  22342. }
  22343. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22344. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22345. if (fastCheck) {
  22346. break;
  22347. }
  22348. }
  22349. }
  22350. }
  22351. else {
  22352. // Triangles test
  22353. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22354. var p0 = positions[indices[index]];
  22355. var p1 = positions[indices[index + 1]];
  22356. var p2 = positions[indices[index + 2]];
  22357. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22358. if (currentIntersectInfo) {
  22359. if (currentIntersectInfo.distance < 0) {
  22360. continue;
  22361. }
  22362. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22363. intersectInfo = currentIntersectInfo;
  22364. intersectInfo.faceId = index / 3;
  22365. if (fastCheck) {
  22366. break;
  22367. }
  22368. }
  22369. }
  22370. }
  22371. }
  22372. return intersectInfo;
  22373. };
  22374. // Clone
  22375. /**
  22376. * Creates a new Submesh from the passed Mesh.
  22377. */
  22378. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22379. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22380. if (!this.IsGlobal) {
  22381. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22382. }
  22383. return result;
  22384. };
  22385. // Dispose
  22386. /**
  22387. * Disposes the Submesh.
  22388. * Returns nothing.
  22389. */
  22390. SubMesh.prototype.dispose = function () {
  22391. if (this._linesIndexBuffer) {
  22392. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22393. this._linesIndexBuffer = null;
  22394. }
  22395. // Remove from mesh
  22396. var index = this._mesh.subMeshes.indexOf(this);
  22397. this._mesh.subMeshes.splice(index, 1);
  22398. };
  22399. // Statics
  22400. /**
  22401. * Creates a new Submesh from the passed parameters :
  22402. * - materialIndex (integer) : the index of the main mesh material.
  22403. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22404. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22405. * - mesh (Mesh) : the main mesh to create the submesh from.
  22406. * - renderingMesh (optional Mesh) : rendering mesh.
  22407. */
  22408. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22409. var minVertexIndex = Number.MAX_VALUE;
  22410. var maxVertexIndex = -Number.MAX_VALUE;
  22411. renderingMesh = renderingMesh || mesh;
  22412. var indices = renderingMesh.getIndices();
  22413. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22414. var vertexIndex = indices[index];
  22415. if (vertexIndex < minVertexIndex)
  22416. minVertexIndex = vertexIndex;
  22417. if (vertexIndex > maxVertexIndex)
  22418. maxVertexIndex = vertexIndex;
  22419. }
  22420. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22421. };
  22422. return SubMesh;
  22423. }(BaseSubMesh));
  22424. BABYLON.SubMesh = SubMesh;
  22425. })(BABYLON || (BABYLON = {}));
  22426. //# sourceMappingURL=babylon.subMesh.js.map
  22427. var BABYLON;
  22428. (function (BABYLON) {
  22429. var EffectFallbacks = (function () {
  22430. function EffectFallbacks() {
  22431. this._defines = {};
  22432. this._currentRank = 32;
  22433. this._maxRank = -1;
  22434. }
  22435. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22436. if (!this._defines[rank]) {
  22437. if (rank < this._currentRank) {
  22438. this._currentRank = rank;
  22439. }
  22440. if (rank > this._maxRank) {
  22441. this._maxRank = rank;
  22442. }
  22443. this._defines[rank] = new Array();
  22444. }
  22445. this._defines[rank].push(define);
  22446. };
  22447. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22448. this._meshRank = rank;
  22449. this._mesh = mesh;
  22450. if (rank < this._currentRank) {
  22451. this._currentRank = rank;
  22452. }
  22453. if (rank > this._maxRank) {
  22454. this._maxRank = rank;
  22455. }
  22456. };
  22457. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22458. get: function () {
  22459. return this._currentRank <= this._maxRank;
  22460. },
  22461. enumerable: true,
  22462. configurable: true
  22463. });
  22464. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22465. // First we try to switch to CPU skinning
  22466. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22467. this._mesh.computeBonesUsingShaders = false;
  22468. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22469. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22470. var scene = this._mesh.getScene();
  22471. for (var index = 0; index < scene.meshes.length; index++) {
  22472. var otherMesh = scene.meshes[index];
  22473. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22474. otherMesh.computeBonesUsingShaders = false;
  22475. }
  22476. }
  22477. }
  22478. else {
  22479. var currentFallbacks = this._defines[this._currentRank];
  22480. if (currentFallbacks) {
  22481. for (var index = 0; index < currentFallbacks.length; index++) {
  22482. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22483. }
  22484. }
  22485. this._currentRank++;
  22486. }
  22487. return currentDefines;
  22488. };
  22489. return EffectFallbacks;
  22490. }());
  22491. BABYLON.EffectFallbacks = EffectFallbacks;
  22492. var EffectCreationOptions = (function () {
  22493. function EffectCreationOptions() {
  22494. }
  22495. return EffectCreationOptions;
  22496. }());
  22497. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22498. var Effect = (function () {
  22499. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22500. var _this = this;
  22501. this.uniqueId = 0;
  22502. this.onCompileObservable = new BABYLON.Observable();
  22503. this.onErrorObservable = new BABYLON.Observable();
  22504. this.onBindObservable = new BABYLON.Observable();
  22505. this._uniformBuffersNames = {};
  22506. this._isReady = false;
  22507. this._compilationError = "";
  22508. this._valueCache = {};
  22509. this.name = baseName;
  22510. if (attributesNamesOrOptions.attributes) {
  22511. var options = attributesNamesOrOptions;
  22512. this._engine = uniformsNamesOrEngine;
  22513. this._attributesNames = options.attributes;
  22514. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22515. this._samplers = options.samplers;
  22516. this.defines = options.defines;
  22517. this.onError = options.onError;
  22518. this.onCompiled = options.onCompiled;
  22519. this._fallbacks = options.fallbacks;
  22520. this._indexParameters = options.indexParameters;
  22521. if (options.uniformBuffersNames) {
  22522. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22523. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22524. }
  22525. }
  22526. }
  22527. else {
  22528. this._engine = engine;
  22529. this.defines = defines;
  22530. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22531. this._samplers = samplers;
  22532. this._attributesNames = attributesNamesOrOptions;
  22533. this.onError = onError;
  22534. this.onCompiled = onCompiled;
  22535. this._indexParameters = indexParameters;
  22536. this._fallbacks = fallbacks;
  22537. }
  22538. this.uniqueId = Effect._uniqueIdSeed++;
  22539. var vertexSource;
  22540. var fragmentSource;
  22541. if (baseName.vertexElement) {
  22542. vertexSource = document.getElementById(baseName.vertexElement);
  22543. if (!vertexSource) {
  22544. vertexSource = baseName.vertexElement;
  22545. }
  22546. }
  22547. else {
  22548. vertexSource = baseName.vertex || baseName;
  22549. }
  22550. if (baseName.fragmentElement) {
  22551. fragmentSource = document.getElementById(baseName.fragmentElement);
  22552. if (!fragmentSource) {
  22553. fragmentSource = baseName.fragmentElement;
  22554. }
  22555. }
  22556. else {
  22557. fragmentSource = baseName.fragment || baseName;
  22558. }
  22559. this._loadVertexShader(vertexSource, function (vertexCode) {
  22560. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22561. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22562. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22563. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22564. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22565. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22566. });
  22567. });
  22568. });
  22569. });
  22570. });
  22571. });
  22572. }
  22573. Object.defineProperty(Effect.prototype, "key", {
  22574. get: function () {
  22575. return this._key;
  22576. },
  22577. enumerable: true,
  22578. configurable: true
  22579. });
  22580. // Properties
  22581. Effect.prototype.isReady = function () {
  22582. return this._isReady;
  22583. };
  22584. Effect.prototype.getProgram = function () {
  22585. return this._program;
  22586. };
  22587. Effect.prototype.getAttributesNames = function () {
  22588. return this._attributesNames;
  22589. };
  22590. Effect.prototype.getAttributeLocation = function (index) {
  22591. return this._attributes[index];
  22592. };
  22593. Effect.prototype.getAttributeLocationByName = function (name) {
  22594. var index = this._attributesNames.indexOf(name);
  22595. return this._attributes[index];
  22596. };
  22597. Effect.prototype.getAttributesCount = function () {
  22598. return this._attributes.length;
  22599. };
  22600. Effect.prototype.getUniformIndex = function (uniformName) {
  22601. return this._uniformsNames.indexOf(uniformName);
  22602. };
  22603. Effect.prototype.getUniform = function (uniformName) {
  22604. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22605. };
  22606. Effect.prototype.getSamplers = function () {
  22607. return this._samplers;
  22608. };
  22609. Effect.prototype.getCompilationError = function () {
  22610. return this._compilationError;
  22611. };
  22612. Effect.prototype.getVertexShaderSource = function () {
  22613. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22614. };
  22615. Effect.prototype.getFragmentShaderSource = function () {
  22616. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22617. };
  22618. // Methods
  22619. Effect.prototype.executeWhenCompiled = function (func) {
  22620. var _this = this;
  22621. if (this.isReady()) {
  22622. func(this);
  22623. return;
  22624. }
  22625. var observer = this.onCompileObservable.add(function (effect) {
  22626. _this.onCompileObservable.remove(observer);
  22627. func(effect);
  22628. });
  22629. };
  22630. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22631. // DOM element ?
  22632. if (vertex instanceof HTMLElement) {
  22633. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22634. callback(vertexCode);
  22635. return;
  22636. }
  22637. // Base64 encoded ?
  22638. if (vertex.substr(0, 7) === "base64:") {
  22639. var vertexBinary = window.atob(vertex.substr(7));
  22640. callback(vertexBinary);
  22641. return;
  22642. }
  22643. // Is in local store ?
  22644. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22645. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22646. return;
  22647. }
  22648. var vertexShaderUrl;
  22649. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22650. vertexShaderUrl = vertex;
  22651. }
  22652. else {
  22653. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22654. }
  22655. // Vertex shader
  22656. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22657. };
  22658. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22659. // DOM element ?
  22660. if (fragment instanceof HTMLElement) {
  22661. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22662. callback(fragmentCode);
  22663. return;
  22664. }
  22665. // Base64 encoded ?
  22666. if (fragment.substr(0, 7) === "base64:") {
  22667. var fragmentBinary = window.atob(fragment.substr(7));
  22668. callback(fragmentBinary);
  22669. return;
  22670. }
  22671. // Is in local store ?
  22672. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22673. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22674. return;
  22675. }
  22676. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22677. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22678. return;
  22679. }
  22680. var fragmentShaderUrl;
  22681. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22682. fragmentShaderUrl = fragment;
  22683. }
  22684. else {
  22685. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22686. }
  22687. // Fragment shader
  22688. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22689. };
  22690. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22691. // Rebuild shaders source code
  22692. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22693. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22694. vertexCode = prefix + vertexCode;
  22695. fragmentCode = prefix + fragmentCode;
  22696. // Number lines of shaders source code
  22697. var i = 2;
  22698. var regex = /\n/gm;
  22699. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22700. i = 2;
  22701. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22702. // Dump shaders name and formatted source code
  22703. if (this.name.vertexElement) {
  22704. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22705. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22706. }
  22707. else if (this.name.vertex) {
  22708. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22709. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22710. }
  22711. else {
  22712. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22713. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22714. }
  22715. };
  22716. ;
  22717. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22718. var preparedSourceCode = this._processPrecision(sourceCode);
  22719. if (this._engine.webGLVersion == 1) {
  22720. callback(preparedSourceCode);
  22721. return;
  22722. }
  22723. // Already converted
  22724. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22725. callback(preparedSourceCode.replace("#version 300 es", ""));
  22726. return;
  22727. }
  22728. // Remove extensions
  22729. // #extension GL_OES_standard_derivatives : enable
  22730. // #extension GL_EXT_shader_texture_lod : enable
  22731. // #extension GL_EXT_frag_depth : enable
  22732. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22733. var result = preparedSourceCode.replace(regex, "");
  22734. // Migrate to GLSL v300
  22735. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22736. result = result.replace(/attribute[ \t]/g, "in ");
  22737. result = result.replace(/[ \t]attribute/g, " in");
  22738. if (isFragment) {
  22739. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22740. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22741. result = result.replace(/texture2D\(/g, "texture(");
  22742. result = result.replace(/textureCube\(/g, "texture(");
  22743. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22744. result = result.replace(/gl_FragColor/g, "glFragColor");
  22745. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22746. }
  22747. callback(result);
  22748. };
  22749. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22750. var _this = this;
  22751. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22752. var match = regex.exec(sourceCode);
  22753. var returnValue = new String(sourceCode);
  22754. while (match != null) {
  22755. var includeFile = match[1];
  22756. // Uniform declaration
  22757. if (includeFile.indexOf("__decl__") !== -1) {
  22758. includeFile = includeFile.replace(/__decl__/, "");
  22759. if (this._engine.webGLVersion != 1) {
  22760. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22761. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22762. }
  22763. includeFile = includeFile + "Declaration";
  22764. }
  22765. if (Effect.IncludesShadersStore[includeFile]) {
  22766. // Substitution
  22767. var includeContent = Effect.IncludesShadersStore[includeFile];
  22768. if (match[2]) {
  22769. var splits = match[3].split(",");
  22770. for (var index = 0; index < splits.length; index += 2) {
  22771. var source = new RegExp(splits[index], "g");
  22772. var dest = splits[index + 1];
  22773. includeContent = includeContent.replace(source, dest);
  22774. }
  22775. }
  22776. if (match[4]) {
  22777. var indexString = match[5];
  22778. if (indexString.indexOf("..") !== -1) {
  22779. var indexSplits = indexString.split("..");
  22780. var minIndex = parseInt(indexSplits[0]);
  22781. var maxIndex = parseInt(indexSplits[1]);
  22782. var sourceIncludeContent = includeContent.slice(0);
  22783. includeContent = "";
  22784. if (isNaN(maxIndex)) {
  22785. maxIndex = this._indexParameters[indexSplits[1]];
  22786. }
  22787. for (var i = minIndex; i < maxIndex; i++) {
  22788. if (this._engine.webGLVersion === 1) {
  22789. // Ubo replacement
  22790. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22791. return p1 + "{X}";
  22792. });
  22793. }
  22794. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22795. }
  22796. }
  22797. else {
  22798. if (this._engine.webGLVersion === 1) {
  22799. // Ubo replacement
  22800. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22801. return p1 + "{X}";
  22802. });
  22803. }
  22804. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22805. }
  22806. }
  22807. // Replace
  22808. returnValue = returnValue.replace(match[0], includeContent);
  22809. }
  22810. else {
  22811. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22812. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22813. Effect.IncludesShadersStore[includeFile] = fileContent;
  22814. _this._processIncludes(returnValue, callback);
  22815. });
  22816. return;
  22817. }
  22818. match = regex.exec(sourceCode);
  22819. }
  22820. callback(returnValue);
  22821. };
  22822. Effect.prototype._processPrecision = function (source) {
  22823. if (source.indexOf("precision highp float") === -1) {
  22824. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22825. source = "precision mediump float;\n" + source;
  22826. }
  22827. else {
  22828. source = "precision highp float;\n" + source;
  22829. }
  22830. }
  22831. else {
  22832. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22833. source = source.replace("precision highp float", "precision mediump float");
  22834. }
  22835. }
  22836. return source;
  22837. };
  22838. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22839. try {
  22840. var engine = this._engine;
  22841. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22842. if (engine.webGLVersion > 1) {
  22843. for (var name in this._uniformBuffersNames) {
  22844. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22845. }
  22846. }
  22847. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22848. this._attributes = engine.getAttributes(this._program, attributesNames);
  22849. var index;
  22850. for (index = 0; index < this._samplers.length; index++) {
  22851. var sampler = this.getUniform(this._samplers[index]);
  22852. if (sampler == null) {
  22853. this._samplers.splice(index, 1);
  22854. index--;
  22855. }
  22856. }
  22857. engine.bindSamplers(this);
  22858. this._compilationError = "";
  22859. this._isReady = true;
  22860. if (this.onCompiled) {
  22861. this.onCompiled(this);
  22862. }
  22863. this.onCompileObservable.notifyObservers(this);
  22864. }
  22865. catch (e) {
  22866. this._compilationError = e.message;
  22867. // Let's go through fallbacks then
  22868. BABYLON.Tools.Error("Unable to compile effect:");
  22869. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22870. return " " + uniform;
  22871. }));
  22872. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22873. return " " + attribute;
  22874. }));
  22875. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22876. BABYLON.Tools.Error("Error: " + this._compilationError);
  22877. if (fallbacks && fallbacks.isMoreFallbacks) {
  22878. BABYLON.Tools.Error("Trying next fallback.");
  22879. defines = fallbacks.reduce(defines);
  22880. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22881. }
  22882. else {
  22883. if (this.onError) {
  22884. this.onError(this, this._compilationError);
  22885. }
  22886. this.onErrorObservable.notifyObservers(this);
  22887. }
  22888. }
  22889. };
  22890. Object.defineProperty(Effect.prototype, "isSupported", {
  22891. get: function () {
  22892. return this._compilationError === "";
  22893. },
  22894. enumerable: true,
  22895. configurable: true
  22896. });
  22897. Effect.prototype._bindTexture = function (channel, texture) {
  22898. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22899. };
  22900. Effect.prototype.setTexture = function (channel, texture) {
  22901. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22902. };
  22903. Effect.prototype.setTextureArray = function (channel, textures) {
  22904. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22905. var initialPos = this._samplers.indexOf(channel);
  22906. for (var index = 1; index < textures.length; index++) {
  22907. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22908. }
  22909. }
  22910. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22911. };
  22912. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22913. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22914. };
  22915. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22916. var cache = this._valueCache[uniformName];
  22917. var flag = matrix.updateFlag;
  22918. if (cache !== undefined && cache === flag) {
  22919. return false;
  22920. }
  22921. this._valueCache[uniformName] = flag;
  22922. return true;
  22923. };
  22924. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22925. var cache = this._valueCache[uniformName];
  22926. if (!cache) {
  22927. cache = [x, y];
  22928. this._valueCache[uniformName] = cache;
  22929. return true;
  22930. }
  22931. var changed = false;
  22932. if (cache[0] !== x) {
  22933. cache[0] = x;
  22934. changed = true;
  22935. }
  22936. if (cache[1] !== y) {
  22937. cache[1] = y;
  22938. changed = true;
  22939. }
  22940. return changed;
  22941. };
  22942. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22943. var cache = this._valueCache[uniformName];
  22944. if (!cache) {
  22945. cache = [x, y, z];
  22946. this._valueCache[uniformName] = cache;
  22947. return true;
  22948. }
  22949. var changed = false;
  22950. if (cache[0] !== x) {
  22951. cache[0] = x;
  22952. changed = true;
  22953. }
  22954. if (cache[1] !== y) {
  22955. cache[1] = y;
  22956. changed = true;
  22957. }
  22958. if (cache[2] !== z) {
  22959. cache[2] = z;
  22960. changed = true;
  22961. }
  22962. return changed;
  22963. };
  22964. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22965. var cache = this._valueCache[uniformName];
  22966. if (!cache) {
  22967. cache = [x, y, z, w];
  22968. this._valueCache[uniformName] = cache;
  22969. return true;
  22970. }
  22971. var changed = false;
  22972. if (cache[0] !== x) {
  22973. cache[0] = x;
  22974. changed = true;
  22975. }
  22976. if (cache[1] !== y) {
  22977. cache[1] = y;
  22978. changed = true;
  22979. }
  22980. if (cache[2] !== z) {
  22981. cache[2] = z;
  22982. changed = true;
  22983. }
  22984. if (cache[3] !== w) {
  22985. cache[3] = w;
  22986. changed = true;
  22987. }
  22988. return changed;
  22989. };
  22990. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22991. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22992. return;
  22993. }
  22994. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22995. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22996. };
  22997. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22998. this._engine.bindUniformBlock(this._program, blockName, index);
  22999. };
  23000. Effect.prototype.setIntArray = function (uniformName, array) {
  23001. this._valueCache[uniformName] = null;
  23002. this._engine.setIntArray(this.getUniform(uniformName), array);
  23003. return this;
  23004. };
  23005. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23006. this._valueCache[uniformName] = null;
  23007. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23008. return this;
  23009. };
  23010. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23011. this._valueCache[uniformName] = null;
  23012. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23013. return this;
  23014. };
  23015. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23016. this._valueCache[uniformName] = null;
  23017. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23018. return this;
  23019. };
  23020. Effect.prototype.setFloatArray = function (uniformName, array) {
  23021. this._valueCache[uniformName] = null;
  23022. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23023. return this;
  23024. };
  23025. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23026. this._valueCache[uniformName] = null;
  23027. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23028. return this;
  23029. };
  23030. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23031. this._valueCache[uniformName] = null;
  23032. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23033. return this;
  23034. };
  23035. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23036. this._valueCache[uniformName] = null;
  23037. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23038. return this;
  23039. };
  23040. Effect.prototype.setArray = function (uniformName, array) {
  23041. this._valueCache[uniformName] = null;
  23042. this._engine.setArray(this.getUniform(uniformName), array);
  23043. return this;
  23044. };
  23045. Effect.prototype.setArray2 = function (uniformName, array) {
  23046. this._valueCache[uniformName] = null;
  23047. this._engine.setArray2(this.getUniform(uniformName), array);
  23048. return this;
  23049. };
  23050. Effect.prototype.setArray3 = function (uniformName, array) {
  23051. this._valueCache[uniformName] = null;
  23052. this._engine.setArray3(this.getUniform(uniformName), array);
  23053. return this;
  23054. };
  23055. Effect.prototype.setArray4 = function (uniformName, array) {
  23056. this._valueCache[uniformName] = null;
  23057. this._engine.setArray4(this.getUniform(uniformName), array);
  23058. return this;
  23059. };
  23060. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23061. if (!matrices) {
  23062. return;
  23063. }
  23064. this._valueCache[uniformName] = null;
  23065. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23066. return this;
  23067. };
  23068. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23069. if (this._cacheMatrix(uniformName, matrix)) {
  23070. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23071. }
  23072. return this;
  23073. };
  23074. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23075. this._valueCache[uniformName] = null;
  23076. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23077. return this;
  23078. };
  23079. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23080. this._valueCache[uniformName] = null;
  23081. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23082. return this;
  23083. };
  23084. Effect.prototype.setFloat = function (uniformName, value) {
  23085. var cache = this._valueCache[uniformName];
  23086. if (cache !== undefined && cache === value)
  23087. return this;
  23088. this._valueCache[uniformName] = value;
  23089. this._engine.setFloat(this.getUniform(uniformName), value);
  23090. return this;
  23091. };
  23092. Effect.prototype.setBool = function (uniformName, bool) {
  23093. var cache = this._valueCache[uniformName];
  23094. if (cache !== undefined && cache === bool)
  23095. return this;
  23096. this._valueCache[uniformName] = bool;
  23097. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23098. return this;
  23099. };
  23100. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23101. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23102. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23103. }
  23104. return this;
  23105. };
  23106. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23107. if (this._cacheFloat2(uniformName, x, y)) {
  23108. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23109. }
  23110. return this;
  23111. };
  23112. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23113. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23114. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23115. }
  23116. return this;
  23117. };
  23118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23119. if (this._cacheFloat3(uniformName, x, y, z)) {
  23120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23121. }
  23122. return this;
  23123. };
  23124. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23125. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23126. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23127. }
  23128. return this;
  23129. };
  23130. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23131. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23132. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23133. }
  23134. return this;
  23135. };
  23136. Effect.prototype.setColor3 = function (uniformName, color3) {
  23137. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23138. this._engine.setColor3(this.getUniform(uniformName), color3);
  23139. }
  23140. return this;
  23141. };
  23142. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23143. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23144. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23145. }
  23146. return this;
  23147. };
  23148. Effect.prototype._recombineShader = function (node) {
  23149. if (node.define) {
  23150. if (node.condition) {
  23151. var defineIndex = this.defines.indexOf("#define " + node.define);
  23152. if (defineIndex === -1) {
  23153. return null;
  23154. }
  23155. var nextComma = this.defines.indexOf("\n", defineIndex);
  23156. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23157. var condition = defineValue + node.condition;
  23158. if (!eval(condition)) {
  23159. return null;
  23160. }
  23161. }
  23162. else if (node.ndef) {
  23163. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23164. return null;
  23165. }
  23166. }
  23167. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23168. return null;
  23169. }
  23170. }
  23171. var result = "";
  23172. for (var index = 0; index < node.children.length; index++) {
  23173. var line = node.children[index];
  23174. if (line.children) {
  23175. var combined = this._recombineShader(line);
  23176. if (combined !== null) {
  23177. result += combined + "\r\n";
  23178. }
  23179. continue;
  23180. }
  23181. if (line.length > 0) {
  23182. result += line + "\r\n";
  23183. }
  23184. }
  23185. return result;
  23186. };
  23187. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23188. var root = {
  23189. children: []
  23190. };
  23191. var currentNode = root;
  23192. var lines = shaderString.split("\n");
  23193. for (var index = 0; index < lines.length; index++) {
  23194. var line = lines[index].trim();
  23195. // #ifdef
  23196. var pos = line.indexOf("#ifdef ");
  23197. if (pos !== -1) {
  23198. var define = line.substr(pos + 7);
  23199. var newNode = {
  23200. condition: null,
  23201. ndef: false,
  23202. define: define,
  23203. children: [],
  23204. parent: currentNode
  23205. };
  23206. currentNode.children.push(newNode);
  23207. currentNode = newNode;
  23208. continue;
  23209. }
  23210. // #ifndef
  23211. var pos = line.indexOf("#ifndef ");
  23212. if (pos !== -1) {
  23213. var define = line.substr(pos + 8);
  23214. newNode = {
  23215. condition: null,
  23216. define: define,
  23217. ndef: true,
  23218. children: [],
  23219. parent: currentNode
  23220. };
  23221. currentNode.children.push(newNode);
  23222. currentNode = newNode;
  23223. continue;
  23224. }
  23225. // #if
  23226. var pos = line.indexOf("#if ");
  23227. if (pos !== -1) {
  23228. var define = line.substr(pos + 4).trim();
  23229. var conditionPos = define.indexOf(" ");
  23230. newNode = {
  23231. condition: define.substr(conditionPos + 1),
  23232. define: define.substr(0, conditionPos),
  23233. ndef: false,
  23234. children: [],
  23235. parent: currentNode
  23236. };
  23237. currentNode.children.push(newNode);
  23238. currentNode = newNode;
  23239. continue;
  23240. }
  23241. // #endif
  23242. pos = line.indexOf("#endif");
  23243. if (pos !== -1) {
  23244. currentNode = currentNode.parent;
  23245. continue;
  23246. }
  23247. currentNode.children.push(line);
  23248. }
  23249. // Recombine
  23250. return this._recombineShader(root);
  23251. };
  23252. return Effect;
  23253. }());
  23254. Effect._uniqueIdSeed = 0;
  23255. Effect._baseCache = {};
  23256. // Statics
  23257. Effect.ShadersStore = {};
  23258. Effect.IncludesShadersStore = {};
  23259. BABYLON.Effect = Effect;
  23260. })(BABYLON || (BABYLON = {}));
  23261. //# sourceMappingURL=babylon.effect.js.map
  23262. var BABYLON;
  23263. (function (BABYLON) {
  23264. var MaterialHelper = (function () {
  23265. function MaterialHelper() {
  23266. }
  23267. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23268. if (defines._areMiscDirty) {
  23269. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23270. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23271. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23272. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23273. }
  23274. };
  23275. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23276. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23277. var changed = false;
  23278. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23279. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23280. changed = true;
  23281. }
  23282. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23283. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23284. changed = true;
  23285. }
  23286. if (defines["INSTANCES"] !== useInstances) {
  23287. defines["INSTANCES"] = useInstances;
  23288. changed = true;
  23289. }
  23290. if (changed) {
  23291. defines.markAsUnprocessed();
  23292. }
  23293. };
  23294. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23295. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23296. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23297. return false;
  23298. }
  23299. defines._normals = defines._needNormals;
  23300. defines._uvs = defines._needUVs;
  23301. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23302. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23303. defines["TANGENT"] = true;
  23304. }
  23305. if (defines._needUVs) {
  23306. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23307. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23308. }
  23309. else {
  23310. defines["UV1"] = false;
  23311. defines["UV2"] = false;
  23312. }
  23313. if (useVertexColor) {
  23314. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23315. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23316. }
  23317. if (useBones) {
  23318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23319. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23320. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23321. }
  23322. else {
  23323. defines["NUM_BONE_INFLUENCERS"] = 0;
  23324. defines["BonesPerMesh"] = 0;
  23325. }
  23326. }
  23327. if (useMorphTargets) {
  23328. if (mesh.morphTargetManager) {
  23329. var manager = mesh.morphTargetManager;
  23330. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23331. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23332. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23333. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23334. }
  23335. else {
  23336. defines["MORPHTARGETS_TANGENT"] = false;
  23337. defines["MORPHTARGETS_NORMAL"] = false;
  23338. defines["MORPHTARGETS"] = false;
  23339. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23340. }
  23341. }
  23342. return true;
  23343. };
  23344. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23345. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23346. if (disableLighting === void 0) { disableLighting = false; }
  23347. if (!defines._areLightsDirty) {
  23348. return defines._needNormals;
  23349. }
  23350. var lightIndex = 0;
  23351. var needNormals = false;
  23352. var needRebuild = false;
  23353. var lightmapMode = false;
  23354. var shadowEnabled = false;
  23355. var specularEnabled = false;
  23356. if (scene.lightsEnabled && !disableLighting) {
  23357. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23358. var light = _a[_i];
  23359. needNormals = true;
  23360. if (defines["LIGHT" + lightIndex] === undefined) {
  23361. needRebuild = true;
  23362. }
  23363. defines["LIGHT" + lightIndex] = true;
  23364. defines["SPOTLIGHT" + lightIndex] = false;
  23365. defines["HEMILIGHT" + lightIndex] = false;
  23366. defines["POINTLIGHT" + lightIndex] = false;
  23367. defines["DIRLIGHT" + lightIndex] = false;
  23368. var type;
  23369. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23370. type = "SPOTLIGHT" + lightIndex;
  23371. }
  23372. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23373. type = "HEMILIGHT" + lightIndex;
  23374. }
  23375. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23376. type = "POINTLIGHT" + lightIndex;
  23377. }
  23378. else {
  23379. type = "DIRLIGHT" + lightIndex;
  23380. }
  23381. defines[type] = true;
  23382. // Specular
  23383. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23384. specularEnabled = true;
  23385. }
  23386. // Shadows
  23387. defines["SHADOW" + lightIndex] = false;
  23388. defines["SHADOWPCF" + lightIndex] = false;
  23389. defines["SHADOWESM" + lightIndex] = false;
  23390. defines["SHADOWCUBE" + lightIndex] = false;
  23391. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23392. var shadowGenerator = light.getShadowGenerator();
  23393. if (shadowGenerator) {
  23394. shadowEnabled = true;
  23395. shadowGenerator.prepareDefines(defines, lightIndex);
  23396. }
  23397. }
  23398. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23399. lightmapMode = true;
  23400. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23401. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23402. }
  23403. else {
  23404. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23405. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23406. }
  23407. lightIndex++;
  23408. if (lightIndex === maxSimultaneousLights)
  23409. break;
  23410. }
  23411. }
  23412. defines["SPECULARTERM"] = specularEnabled;
  23413. defines["SHADOWS"] = shadowEnabled;
  23414. // Resetting all other lights if any
  23415. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23416. if (defines["LIGHT" + index] !== undefined) {
  23417. defines["LIGHT" + index] = false;
  23418. }
  23419. }
  23420. var caps = scene.getEngine().getCaps();
  23421. if (defines["SHADOWFLOAT"] === undefined) {
  23422. needRebuild = true;
  23423. }
  23424. defines["SHADOWFLOAT"] = shadowEnabled &&
  23425. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23426. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23427. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23428. if (needRebuild) {
  23429. defines.rebuild();
  23430. }
  23431. return needNormals;
  23432. };
  23433. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23434. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23435. var uniformsList, uniformBuffersList, samplersList, defines;
  23436. if (uniformsListOrOptions.uniformsNames) {
  23437. var options = uniformsListOrOptions;
  23438. uniformsList = options.uniformsNames;
  23439. uniformBuffersList = options.uniformBuffersNames;
  23440. samplersList = options.samplers;
  23441. defines = options.defines;
  23442. maxSimultaneousLights = options.maxSimultaneousLights;
  23443. }
  23444. else {
  23445. uniformsList = uniformsListOrOptions;
  23446. }
  23447. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23448. if (!defines["LIGHT" + lightIndex]) {
  23449. break;
  23450. }
  23451. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23452. if (uniformBuffersList) {
  23453. uniformBuffersList.push("Light" + lightIndex);
  23454. }
  23455. samplersList.push("shadowSampler" + lightIndex);
  23456. }
  23457. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23458. uniformsList.push("morphTargetInfluences");
  23459. }
  23460. };
  23461. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23462. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23463. if (!defines["SHADOWS"]) {
  23464. return;
  23465. }
  23466. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23467. if (!defines["LIGHT" + lightIndex]) {
  23468. break;
  23469. }
  23470. if (lightIndex > 0) {
  23471. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23472. }
  23473. if (defines["SHADOW" + lightIndex]) {
  23474. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23475. }
  23476. if (defines["SHADOWPCF" + lightIndex]) {
  23477. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23478. }
  23479. if (defines["SHADOWESM" + lightIndex]) {
  23480. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23481. }
  23482. }
  23483. };
  23484. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23485. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23486. if (influencers > 0) {
  23487. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23488. var manager = mesh.morphTargetManager;
  23489. var normal = manager.supportsNormals && defines["NORMAL"];
  23490. var tangent = manager.supportsTangents && defines["TANGENT"];
  23491. for (var index = 0; index < influencers; index++) {
  23492. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23493. if (normal) {
  23494. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23495. }
  23496. if (tangent) {
  23497. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23498. }
  23499. if (attribs.length > maxAttributesCount) {
  23500. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23501. }
  23502. }
  23503. }
  23504. };
  23505. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23506. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23507. fallbacks.addCPUSkinningFallback(0, mesh);
  23508. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23509. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23510. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23511. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23512. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23513. }
  23514. }
  23515. };
  23516. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23517. if (defines["INSTANCES"]) {
  23518. attribs.push("world0");
  23519. attribs.push("world1");
  23520. attribs.push("world2");
  23521. attribs.push("world3");
  23522. }
  23523. };
  23524. // Bindings
  23525. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23526. if (light.shadowEnabled && mesh.receiveShadows) {
  23527. var shadowGenerator = light.getShadowGenerator();
  23528. if (shadowGenerator) {
  23529. shadowGenerator.bindShadowLight(lightIndex, effect);
  23530. }
  23531. }
  23532. };
  23533. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23534. light.transferToEffect(effect, lightIndex + "");
  23535. };
  23536. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23537. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23538. var lightIndex = 0;
  23539. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23540. var light = _a[_i];
  23541. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23542. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23543. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23544. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23545. if (defines["SPECULARTERM"]) {
  23546. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23547. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23548. }
  23549. // Shadows
  23550. if (scene.shadowsEnabled) {
  23551. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23552. }
  23553. light._uniformBuffer.update();
  23554. lightIndex++;
  23555. if (lightIndex === maxSimultaneousLights)
  23556. break;
  23557. }
  23558. };
  23559. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23560. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23561. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23562. effect.setColor3("vFogColor", scene.fogColor);
  23563. }
  23564. };
  23565. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23566. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23567. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23568. if (matrices) {
  23569. effect.setMatrices("mBones", matrices);
  23570. }
  23571. }
  23572. };
  23573. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23574. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23575. return;
  23576. }
  23577. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23578. };
  23579. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23580. if (defines["LOGARITHMICDEPTH"]) {
  23581. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23582. }
  23583. };
  23584. MaterialHelper.BindClipPlane = function (effect, scene) {
  23585. if (scene.clipPlane) {
  23586. var clipPlane = scene.clipPlane;
  23587. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23588. }
  23589. };
  23590. return MaterialHelper;
  23591. }());
  23592. BABYLON.MaterialHelper = MaterialHelper;
  23593. })(BABYLON || (BABYLON = {}));
  23594. //# sourceMappingURL=babylon.materialHelper.js.map
  23595. var BABYLON;
  23596. (function (BABYLON) {
  23597. var MaterialDefines = (function () {
  23598. function MaterialDefines() {
  23599. this._isDirty = true;
  23600. this._areLightsDirty = true;
  23601. this._areAttributesDirty = true;
  23602. this._areTexturesDirty = true;
  23603. this._areFresnelDirty = true;
  23604. this._areMiscDirty = true;
  23605. this._normals = false;
  23606. this._uvs = false;
  23607. this._needNormals = false;
  23608. this._needUVs = false;
  23609. }
  23610. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23611. get: function () {
  23612. return this._isDirty;
  23613. },
  23614. enumerable: true,
  23615. configurable: true
  23616. });
  23617. MaterialDefines.prototype.markAsProcessed = function () {
  23618. this._isDirty = false;
  23619. this._areAttributesDirty = false;
  23620. this._areTexturesDirty = false;
  23621. this._areFresnelDirty = false;
  23622. this._areLightsDirty = false;
  23623. this._areMiscDirty = false;
  23624. };
  23625. MaterialDefines.prototype.markAsUnprocessed = function () {
  23626. this._isDirty = true;
  23627. };
  23628. MaterialDefines.prototype.markAllAsDirty = function () {
  23629. this._areTexturesDirty = true;
  23630. this._areAttributesDirty = true;
  23631. this._areLightsDirty = true;
  23632. this._areFresnelDirty = true;
  23633. this._areMiscDirty = true;
  23634. this._isDirty = true;
  23635. };
  23636. MaterialDefines.prototype.markAsLightDirty = function () {
  23637. this._areLightsDirty = true;
  23638. this._isDirty = true;
  23639. };
  23640. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23641. this._areAttributesDirty = true;
  23642. this._isDirty = true;
  23643. };
  23644. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23645. this._areTexturesDirty = true;
  23646. this._isDirty = true;
  23647. };
  23648. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23649. this._areFresnelDirty = true;
  23650. this._isDirty = true;
  23651. };
  23652. MaterialDefines.prototype.markAsMiscDirty = function () {
  23653. this._areMiscDirty = true;
  23654. this._isDirty = true;
  23655. };
  23656. MaterialDefines.prototype.rebuild = function () {
  23657. if (this._keys) {
  23658. delete this._keys;
  23659. }
  23660. this._keys = [];
  23661. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23662. var key = _a[_i];
  23663. if (key[0] === "_") {
  23664. continue;
  23665. }
  23666. this._keys.push(key);
  23667. }
  23668. };
  23669. MaterialDefines.prototype.isEqual = function (other) {
  23670. if (this._keys.length !== other._keys.length) {
  23671. return false;
  23672. }
  23673. for (var index = 0; index < this._keys.length; index++) {
  23674. var prop = this._keys[index];
  23675. if (this[prop] !== other[prop]) {
  23676. return false;
  23677. }
  23678. }
  23679. return true;
  23680. };
  23681. MaterialDefines.prototype.cloneTo = function (other) {
  23682. if (this._keys.length !== other._keys.length) {
  23683. other._keys = this._keys.slice(0);
  23684. }
  23685. for (var index = 0; index < this._keys.length; index++) {
  23686. var prop = this._keys[index];
  23687. other[prop] = this[prop];
  23688. }
  23689. };
  23690. MaterialDefines.prototype.reset = function () {
  23691. for (var index = 0; index < this._keys.length; index++) {
  23692. var prop = this._keys[index];
  23693. if (typeof (this[prop]) === "number") {
  23694. this[prop] = 0;
  23695. }
  23696. else {
  23697. this[prop] = false;
  23698. }
  23699. }
  23700. };
  23701. MaterialDefines.prototype.toString = function () {
  23702. var result = "";
  23703. for (var index = 0; index < this._keys.length; index++) {
  23704. var prop = this._keys[index];
  23705. var value = this[prop];
  23706. if (typeof (value) === "number") {
  23707. result += "#define " + prop + " " + this[prop] + "\n";
  23708. }
  23709. else if (value) {
  23710. result += "#define " + prop + "\n";
  23711. }
  23712. }
  23713. return result;
  23714. };
  23715. return MaterialDefines;
  23716. }());
  23717. BABYLON.MaterialDefines = MaterialDefines;
  23718. var Material = (function () {
  23719. function Material(name, scene, doNotAdd) {
  23720. this.checkReadyOnEveryCall = false;
  23721. this.checkReadyOnlyOnce = false;
  23722. this.state = "";
  23723. this.alpha = 1.0;
  23724. this._backFaceCulling = true;
  23725. this.doNotSerialize = false;
  23726. this.storeEffectOnSubMeshes = false;
  23727. /**
  23728. * An event triggered when the material is disposed.
  23729. * @type {BABYLON.Observable}
  23730. */
  23731. this.onDisposeObservable = new BABYLON.Observable();
  23732. /**
  23733. * An event triggered when the material is bound.
  23734. * @type {BABYLON.Observable}
  23735. */
  23736. this.onBindObservable = new BABYLON.Observable();
  23737. /**
  23738. * An event triggered when the material is unbound.
  23739. * @type {BABYLON.Observable}
  23740. */
  23741. this.onUnBindObservable = new BABYLON.Observable();
  23742. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23743. this.disableDepthWrite = false;
  23744. this._fogEnabled = true;
  23745. this.pointSize = 1.0;
  23746. this.zOffset = 0;
  23747. this._wasPreviouslyReady = false;
  23748. this._fillMode = Material.TriangleFillMode;
  23749. this.name = name;
  23750. this.id = name;
  23751. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23752. if (this._scene.useRightHandedSystem) {
  23753. this.sideOrientation = Material.ClockWiseSideOrientation;
  23754. }
  23755. else {
  23756. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23757. }
  23758. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23759. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23760. if (!doNotAdd) {
  23761. this._scene.materials.push(this);
  23762. }
  23763. }
  23764. Object.defineProperty(Material, "TriangleFillMode", {
  23765. get: function () {
  23766. return Material._TriangleFillMode;
  23767. },
  23768. enumerable: true,
  23769. configurable: true
  23770. });
  23771. Object.defineProperty(Material, "WireFrameFillMode", {
  23772. get: function () {
  23773. return Material._WireFrameFillMode;
  23774. },
  23775. enumerable: true,
  23776. configurable: true
  23777. });
  23778. Object.defineProperty(Material, "PointFillMode", {
  23779. get: function () {
  23780. return Material._PointFillMode;
  23781. },
  23782. enumerable: true,
  23783. configurable: true
  23784. });
  23785. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23786. get: function () {
  23787. return Material._ClockWiseSideOrientation;
  23788. },
  23789. enumerable: true,
  23790. configurable: true
  23791. });
  23792. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23793. get: function () {
  23794. return Material._CounterClockWiseSideOrientation;
  23795. },
  23796. enumerable: true,
  23797. configurable: true
  23798. });
  23799. Object.defineProperty(Material, "TextureDirtyFlag", {
  23800. get: function () {
  23801. return Material._TextureDirtyFlag;
  23802. },
  23803. enumerable: true,
  23804. configurable: true
  23805. });
  23806. Object.defineProperty(Material, "LightDirtyFlag", {
  23807. get: function () {
  23808. return Material._LightDirtyFlag;
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23814. get: function () {
  23815. return Material._FresnelDirtyFlag;
  23816. },
  23817. enumerable: true,
  23818. configurable: true
  23819. });
  23820. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23821. get: function () {
  23822. return Material._AttributesDirtyFlag;
  23823. },
  23824. enumerable: true,
  23825. configurable: true
  23826. });
  23827. Object.defineProperty(Material, "MiscDirtyFlag", {
  23828. get: function () {
  23829. return Material._MiscDirtyFlag;
  23830. },
  23831. enumerable: true,
  23832. configurable: true
  23833. });
  23834. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23835. get: function () {
  23836. return this._backFaceCulling;
  23837. },
  23838. set: function (value) {
  23839. if (this._backFaceCulling === value) {
  23840. return;
  23841. }
  23842. this._backFaceCulling = value;
  23843. this.markAsDirty(Material.TextureDirtyFlag);
  23844. },
  23845. enumerable: true,
  23846. configurable: true
  23847. });
  23848. Object.defineProperty(Material.prototype, "onDispose", {
  23849. set: function (callback) {
  23850. if (this._onDisposeObserver) {
  23851. this.onDisposeObservable.remove(this._onDisposeObserver);
  23852. }
  23853. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. Object.defineProperty(Material.prototype, "onBind", {
  23859. set: function (callback) {
  23860. if (this._onBindObserver) {
  23861. this.onBindObservable.remove(this._onBindObserver);
  23862. }
  23863. this._onBindObserver = this.onBindObservable.add(callback);
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. Object.defineProperty(Material.prototype, "fogEnabled", {
  23869. get: function () {
  23870. return this._fogEnabled;
  23871. },
  23872. set: function (value) {
  23873. if (this._fogEnabled === value) {
  23874. return;
  23875. }
  23876. this._fogEnabled = value;
  23877. this.markAsDirty(Material.MiscDirtyFlag);
  23878. },
  23879. enumerable: true,
  23880. configurable: true
  23881. });
  23882. Object.defineProperty(Material.prototype, "wireframe", {
  23883. get: function () {
  23884. return this._fillMode === Material.WireFrameFillMode;
  23885. },
  23886. set: function (value) {
  23887. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23888. },
  23889. enumerable: true,
  23890. configurable: true
  23891. });
  23892. Object.defineProperty(Material.prototype, "pointsCloud", {
  23893. get: function () {
  23894. return this._fillMode === Material.PointFillMode;
  23895. },
  23896. set: function (value) {
  23897. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. Object.defineProperty(Material.prototype, "fillMode", {
  23903. get: function () {
  23904. return this._fillMode;
  23905. },
  23906. set: function (value) {
  23907. if (this._fillMode === value) {
  23908. return;
  23909. }
  23910. this._fillMode = value;
  23911. this.markAsDirty(Material.MiscDirtyFlag);
  23912. },
  23913. enumerable: true,
  23914. configurable: true
  23915. });
  23916. /**
  23917. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23918. * subclasses should override adding information pertainent to themselves
  23919. */
  23920. Material.prototype.toString = function (fullDetails) {
  23921. var ret = "Name: " + this.name;
  23922. if (fullDetails) {
  23923. }
  23924. return ret;
  23925. };
  23926. /**
  23927. * Child classes can use it to update shaders
  23928. */
  23929. Material.prototype.getClassName = function () {
  23930. return "Material";
  23931. };
  23932. Object.defineProperty(Material.prototype, "isFrozen", {
  23933. get: function () {
  23934. return this.checkReadyOnlyOnce;
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. Material.prototype.freeze = function () {
  23940. this.checkReadyOnlyOnce = true;
  23941. };
  23942. Material.prototype.unfreeze = function () {
  23943. this.checkReadyOnlyOnce = false;
  23944. };
  23945. Material.prototype.isReady = function (mesh, useInstances) {
  23946. return true;
  23947. };
  23948. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23949. return false;
  23950. };
  23951. Material.prototype.getEffect = function () {
  23952. return this._effect;
  23953. };
  23954. Material.prototype.getScene = function () {
  23955. return this._scene;
  23956. };
  23957. Material.prototype.needAlphaBlending = function () {
  23958. return (this.alpha < 1.0);
  23959. };
  23960. Material.prototype.needAlphaTesting = function () {
  23961. return false;
  23962. };
  23963. Material.prototype.getAlphaTestTexture = function () {
  23964. return null;
  23965. };
  23966. Material.prototype.markDirty = function () {
  23967. this._wasPreviouslyReady = false;
  23968. };
  23969. Material.prototype._preBind = function (effect) {
  23970. var engine = this._scene.getEngine();
  23971. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23972. engine.enableEffect(effect ? effect : this._effect);
  23973. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23974. };
  23975. Material.prototype.bind = function (world, mesh) {
  23976. };
  23977. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23978. };
  23979. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23980. };
  23981. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23982. sceneUbo.bindToEffect(effect, "Scene");
  23983. };
  23984. Material.prototype.bindView = function (effect) {
  23985. if (!this._useUBO) {
  23986. effect.setMatrix("view", this.getScene().getViewMatrix());
  23987. }
  23988. else {
  23989. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23990. }
  23991. };
  23992. Material.prototype.bindViewProjection = function (effect) {
  23993. if (!this._useUBO) {
  23994. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23995. }
  23996. else {
  23997. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23998. }
  23999. };
  24000. Material.prototype._afterBind = function (mesh) {
  24001. this._scene._cachedMaterial = this;
  24002. this.onBindObservable.notifyObservers(mesh);
  24003. if (this.disableDepthWrite) {
  24004. var engine = this._scene.getEngine();
  24005. this._cachedDepthWriteState = engine.getDepthWrite();
  24006. engine.setDepthWrite(false);
  24007. }
  24008. };
  24009. Material.prototype.unbind = function () {
  24010. this.onUnBindObservable.notifyObservers(this);
  24011. if (this.disableDepthWrite) {
  24012. var engine = this._scene.getEngine();
  24013. engine.setDepthWrite(this._cachedDepthWriteState);
  24014. }
  24015. };
  24016. Material.prototype.clone = function (name) {
  24017. return null;
  24018. };
  24019. Material.prototype.getBindedMeshes = function () {
  24020. var result = new Array();
  24021. for (var index = 0; index < this._scene.meshes.length; index++) {
  24022. var mesh = this._scene.meshes[index];
  24023. if (mesh.material === this) {
  24024. result.push(mesh);
  24025. }
  24026. }
  24027. return result;
  24028. };
  24029. // Force shader compilation including textures ready check
  24030. Material.prototype.forceCompilation = function (mesh, onCompiled) {
  24031. var _this = this;
  24032. var subMesh = new BABYLON.BaseSubMesh();
  24033. var scene = this.getScene();
  24034. var beforeRenderCallback = function () {
  24035. if (subMesh._materialDefines) {
  24036. subMesh._materialDefines._renderId = -1;
  24037. }
  24038. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24039. scene.unregisterBeforeRender(beforeRenderCallback);
  24040. if (onCompiled) {
  24041. onCompiled(_this);
  24042. }
  24043. }
  24044. };
  24045. scene.registerBeforeRender(beforeRenderCallback);
  24046. };
  24047. Material.prototype.markAsDirty = function (flag) {
  24048. if (flag & Material.TextureDirtyFlag) {
  24049. this._markAllSubMeshesAsTexturesDirty();
  24050. }
  24051. if (flag & Material.LightDirtyFlag) {
  24052. this._markAllSubMeshesAsLightsDirty();
  24053. }
  24054. if (flag & Material.FresnelDirtyFlag) {
  24055. this._markAllSubMeshesAsFresnelDirty();
  24056. }
  24057. if (flag & Material.AttributesDirtyFlag) {
  24058. this._markAllSubMeshesAsAttributesDirty();
  24059. }
  24060. if (flag & Material.MiscDirtyFlag) {
  24061. this._markAllSubMeshesAsMiscDirty();
  24062. }
  24063. this.getScene().resetCachedMaterial();
  24064. };
  24065. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24066. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24067. var mesh = _a[_i];
  24068. if (!mesh.subMeshes) {
  24069. continue;
  24070. }
  24071. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24072. var subMesh = _c[_b];
  24073. if (subMesh.getMaterial() !== this) {
  24074. continue;
  24075. }
  24076. if (!subMesh._materialDefines) {
  24077. return;
  24078. }
  24079. func(subMesh._materialDefines);
  24080. }
  24081. }
  24082. };
  24083. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24084. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24085. };
  24086. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24087. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24088. };
  24089. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24090. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24091. };
  24092. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24093. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24094. };
  24095. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24096. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24097. };
  24098. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24099. // Animations
  24100. this.getScene().stopAnimation(this);
  24101. // Remove from scene
  24102. var index = this._scene.materials.indexOf(this);
  24103. if (index >= 0) {
  24104. this._scene.materials.splice(index, 1);
  24105. }
  24106. // Remove from meshes
  24107. for (index = 0; index < this._scene.meshes.length; index++) {
  24108. var mesh = this._scene.meshes[index];
  24109. if (mesh.material === this) {
  24110. mesh.material = null;
  24111. if (mesh.geometry) {
  24112. var geometry = mesh.geometry;
  24113. if (this.storeEffectOnSubMeshes) {
  24114. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24115. var subMesh = _a[_i];
  24116. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24117. }
  24118. }
  24119. else {
  24120. geometry._releaseVertexArrayObject(this._effect);
  24121. }
  24122. }
  24123. }
  24124. }
  24125. this._uniformBuffer.dispose();
  24126. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24127. if (forceDisposeEffect && this._effect) {
  24128. if (this.storeEffectOnSubMeshes) {
  24129. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24130. var subMesh = _c[_b];
  24131. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24132. }
  24133. }
  24134. else {
  24135. this._scene.getEngine()._releaseEffect(this._effect);
  24136. }
  24137. this._effect = null;
  24138. }
  24139. // Callback
  24140. this.onDisposeObservable.notifyObservers(this);
  24141. this.onDisposeObservable.clear();
  24142. this.onBindObservable.clear();
  24143. this.onUnBindObservable.clear();
  24144. };
  24145. Material.prototype.serialize = function () {
  24146. return BABYLON.SerializationHelper.Serialize(this);
  24147. };
  24148. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24149. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24150. multiMaterial.id = parsedMultiMaterial.id;
  24151. if (BABYLON.Tags) {
  24152. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24153. }
  24154. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24155. var subMatId = parsedMultiMaterial.materials[matIndex];
  24156. if (subMatId) {
  24157. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24158. }
  24159. else {
  24160. multiMaterial.subMaterials.push(null);
  24161. }
  24162. }
  24163. return multiMaterial;
  24164. };
  24165. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24166. if (!parsedMaterial.customType) {
  24167. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24168. }
  24169. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24170. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24171. if (!BABYLON.LegacyPBRMaterial) {
  24172. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24173. return;
  24174. }
  24175. }
  24176. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24177. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24178. ;
  24179. };
  24180. return Material;
  24181. }());
  24182. Material._TriangleFillMode = 0;
  24183. Material._WireFrameFillMode = 1;
  24184. Material._PointFillMode = 2;
  24185. Material._ClockWiseSideOrientation = 0;
  24186. Material._CounterClockWiseSideOrientation = 1;
  24187. Material._TextureDirtyFlag = 1;
  24188. Material._LightDirtyFlag = 2;
  24189. Material._FresnelDirtyFlag = 4;
  24190. Material._AttributesDirtyFlag = 8;
  24191. Material._MiscDirtyFlag = 16;
  24192. __decorate([
  24193. BABYLON.serialize()
  24194. ], Material.prototype, "id", void 0);
  24195. __decorate([
  24196. BABYLON.serialize()
  24197. ], Material.prototype, "name", void 0);
  24198. __decorate([
  24199. BABYLON.serialize()
  24200. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24201. __decorate([
  24202. BABYLON.serialize()
  24203. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24204. __decorate([
  24205. BABYLON.serialize()
  24206. ], Material.prototype, "state", void 0);
  24207. __decorate([
  24208. BABYLON.serialize()
  24209. ], Material.prototype, "alpha", void 0);
  24210. __decorate([
  24211. BABYLON.serialize("backFaceCulling")
  24212. ], Material.prototype, "_backFaceCulling", void 0);
  24213. __decorate([
  24214. BABYLON.serialize()
  24215. ], Material.prototype, "sideOrientation", void 0);
  24216. __decorate([
  24217. BABYLON.serialize()
  24218. ], Material.prototype, "alphaMode", void 0);
  24219. __decorate([
  24220. BABYLON.serialize()
  24221. ], Material.prototype, "disableDepthWrite", void 0);
  24222. __decorate([
  24223. BABYLON.serialize("fogEnabled")
  24224. ], Material.prototype, "_fogEnabled", void 0);
  24225. __decorate([
  24226. BABYLON.serialize()
  24227. ], Material.prototype, "pointSize", void 0);
  24228. __decorate([
  24229. BABYLON.serialize()
  24230. ], Material.prototype, "zOffset", void 0);
  24231. __decorate([
  24232. BABYLON.serialize()
  24233. ], Material.prototype, "wireframe", null);
  24234. __decorate([
  24235. BABYLON.serialize()
  24236. ], Material.prototype, "pointsCloud", null);
  24237. __decorate([
  24238. BABYLON.serialize()
  24239. ], Material.prototype, "fillMode", null);
  24240. BABYLON.Material = Material;
  24241. })(BABYLON || (BABYLON = {}));
  24242. //# sourceMappingURL=babylon.material.js.map
  24243. var BABYLON;
  24244. (function (BABYLON) {
  24245. var UniformBuffer = (function () {
  24246. /**
  24247. * Uniform buffer objects.
  24248. *
  24249. * Handles blocks of uniform on the GPU.
  24250. *
  24251. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24252. *
  24253. * For more information, please refer to :
  24254. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24255. */
  24256. function UniformBuffer(engine, data, dynamic) {
  24257. this._engine = engine;
  24258. this._noUBO = engine.webGLVersion === 1;
  24259. this._dynamic = dynamic;
  24260. this._data = data || [];
  24261. this._uniformLocations = {};
  24262. this._uniformSizes = {};
  24263. this._uniformLocationPointer = 0;
  24264. this._needSync = false;
  24265. if (this._noUBO) {
  24266. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24267. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24268. this.updateFloat = this._updateFloatForEffect;
  24269. this.updateFloat2 = this._updateFloat2ForEffect;
  24270. this.updateFloat3 = this._updateFloat3ForEffect;
  24271. this.updateFloat4 = this._updateFloat4ForEffect;
  24272. this.updateMatrix = this._updateMatrixForEffect;
  24273. this.updateVector3 = this._updateVector3ForEffect;
  24274. this.updateVector4 = this._updateVector4ForEffect;
  24275. this.updateColor3 = this._updateColor3ForEffect;
  24276. this.updateColor4 = this._updateColor4ForEffect;
  24277. }
  24278. else {
  24279. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24280. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24281. this.updateFloat = this._updateFloatForUniform;
  24282. this.updateFloat2 = this._updateFloat2ForUniform;
  24283. this.updateFloat3 = this._updateFloat3ForUniform;
  24284. this.updateFloat4 = this._updateFloat4ForUniform;
  24285. this.updateMatrix = this._updateMatrixForUniform;
  24286. this.updateVector3 = this._updateVector3ForUniform;
  24287. this.updateVector4 = this._updateVector4ForUniform;
  24288. this.updateColor3 = this._updateColor3ForUniform;
  24289. this.updateColor4 = this._updateColor4ForUniform;
  24290. }
  24291. }
  24292. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24293. // Properties
  24294. /**
  24295. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24296. * or just falling back on setUniformXXX calls.
  24297. */
  24298. get: function () {
  24299. return !this._noUBO;
  24300. },
  24301. enumerable: true,
  24302. configurable: true
  24303. });
  24304. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24305. /**
  24306. * Indicates if the WebGL underlying uniform buffer is in sync
  24307. * with the javascript cache data.
  24308. */
  24309. get: function () {
  24310. return !this._needSync;
  24311. },
  24312. enumerable: true,
  24313. configurable: true
  24314. });
  24315. /**
  24316. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24317. * Also, a dynamic UniformBuffer will disable cache verification and always
  24318. * update the underlying WebGL uniform buffer to the GPU.
  24319. */
  24320. UniformBuffer.prototype.isDynamic = function () {
  24321. return this._dynamic;
  24322. };
  24323. /**
  24324. * The data cache on JS side.
  24325. */
  24326. UniformBuffer.prototype.getData = function () {
  24327. return this._bufferData;
  24328. };
  24329. /**
  24330. * The underlying WebGL Uniform buffer.
  24331. */
  24332. UniformBuffer.prototype.getBuffer = function () {
  24333. return this._buffer;
  24334. };
  24335. /**
  24336. * std140 layout specifies how to align data within an UBO structure.
  24337. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24338. * for specs.
  24339. */
  24340. UniformBuffer.prototype._fillAlignment = function (size) {
  24341. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24342. // and 4x4 matrices
  24343. // TODO : change if other types are used
  24344. var alignment;
  24345. if (size <= 2) {
  24346. alignment = size;
  24347. }
  24348. else {
  24349. alignment = 4;
  24350. }
  24351. if ((this._uniformLocationPointer % alignment) !== 0) {
  24352. var oldPointer = this._uniformLocationPointer;
  24353. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24354. var diff = this._uniformLocationPointer - oldPointer;
  24355. for (var i = 0; i < diff; i++) {
  24356. this._data.push(0);
  24357. }
  24358. }
  24359. };
  24360. /**
  24361. * Adds an uniform in the buffer.
  24362. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24363. * for the layout to be correct !
  24364. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24365. * @param {number|number[]} size Data size, or data directly.
  24366. */
  24367. UniformBuffer.prototype.addUniform = function (name, size) {
  24368. if (this._noUBO) {
  24369. return;
  24370. }
  24371. if (this._uniformLocations[name] !== undefined) {
  24372. // Already existing uniform
  24373. return;
  24374. }
  24375. // This function must be called in the order of the shader layout !
  24376. // size can be the size of the uniform, or data directly
  24377. var data;
  24378. if (size instanceof Array) {
  24379. data = size;
  24380. size = data.length;
  24381. }
  24382. else {
  24383. size = size;
  24384. data = [];
  24385. // Fill with zeros
  24386. for (var i = 0; i < size; i++) {
  24387. data.push(0);
  24388. }
  24389. }
  24390. this._fillAlignment(size);
  24391. this._uniformSizes[name] = size;
  24392. this._uniformLocations[name] = this._uniformLocationPointer;
  24393. this._uniformLocationPointer += size;
  24394. for (var i = 0; i < size; i++) {
  24395. this._data.push(data[i]);
  24396. }
  24397. this._needSync = true;
  24398. };
  24399. /**
  24400. * Wrapper for addUniform.
  24401. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24402. * @param {Matrix} mat A 4x4 matrix.
  24403. */
  24404. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24405. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24406. };
  24407. /**
  24408. * Wrapper for addUniform.
  24409. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24410. * @param {number} x
  24411. * @param {number} y
  24412. */
  24413. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24414. var temp = [x, y];
  24415. this.addUniform(name, temp);
  24416. };
  24417. /**
  24418. * Wrapper for addUniform.
  24419. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24420. * @param {number} x
  24421. * @param {number} y
  24422. * @param {number} z
  24423. */
  24424. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24425. var temp = [x, y, z];
  24426. this.addUniform(name, temp);
  24427. };
  24428. /**
  24429. * Wrapper for addUniform.
  24430. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24431. * @param {Color3} color
  24432. */
  24433. UniformBuffer.prototype.addColor3 = function (name, color) {
  24434. var temp = [];
  24435. color.toArray(temp);
  24436. this.addUniform(name, temp);
  24437. };
  24438. /**
  24439. * Wrapper for addUniform.
  24440. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24441. * @param {Color3} color
  24442. * @param {number} alpha
  24443. */
  24444. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24445. var temp = [];
  24446. color.toArray(temp);
  24447. temp.push(alpha);
  24448. this.addUniform(name, temp);
  24449. };
  24450. /**
  24451. * Wrapper for addUniform.
  24452. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24453. * @param {Vector3} vector
  24454. */
  24455. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24456. var temp = [];
  24457. vector.toArray(temp);
  24458. this.addUniform(name, temp);
  24459. };
  24460. /**
  24461. * Wrapper for addUniform.
  24462. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24463. */
  24464. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24465. this.addUniform(name, 12);
  24466. };
  24467. /**
  24468. * Wrapper for addUniform.
  24469. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24470. */
  24471. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24472. this.addUniform(name, 8);
  24473. };
  24474. /**
  24475. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24476. */
  24477. UniformBuffer.prototype.create = function () {
  24478. if (this._noUBO) {
  24479. return;
  24480. }
  24481. if (this._buffer) {
  24482. return; // nothing to do
  24483. }
  24484. // See spec, alignment must be filled as a vec4
  24485. this._fillAlignment(4);
  24486. this._bufferData = new Float32Array(this._data);
  24487. if (this._dynamic) {
  24488. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24489. }
  24490. else {
  24491. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24492. }
  24493. this._needSync = true;
  24494. };
  24495. /**
  24496. * Updates the WebGL Uniform Buffer on the GPU.
  24497. * If the `dynamic` flag is set to true, no cache comparison is done.
  24498. * Otherwise, the buffer will be updated only if the cache differs.
  24499. */
  24500. UniformBuffer.prototype.update = function () {
  24501. if (!this._buffer) {
  24502. this.create();
  24503. return;
  24504. }
  24505. if (!this._dynamic && !this._needSync) {
  24506. return;
  24507. }
  24508. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24509. this._needSync = false;
  24510. };
  24511. /**
  24512. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24513. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24514. * @param {number[]|Float32Array} data Flattened data
  24515. * @param {number} size Size of the data.
  24516. */
  24517. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24518. var location = this._uniformLocations[uniformName];
  24519. if (location === undefined) {
  24520. if (this._buffer) {
  24521. // Cannot add an uniform if the buffer is already created
  24522. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24523. return;
  24524. }
  24525. this.addUniform(uniformName, size);
  24526. location = this._uniformLocations[uniformName];
  24527. }
  24528. if (!this._buffer) {
  24529. this.create();
  24530. }
  24531. if (!this._dynamic) {
  24532. // Cache for static uniform buffers
  24533. var changed = false;
  24534. for (var i = 0; i < size; i++) {
  24535. if (this._bufferData[location + i] !== data[i]) {
  24536. changed = true;
  24537. this._bufferData[location + i] = data[i];
  24538. }
  24539. }
  24540. this._needSync = this._needSync || changed;
  24541. }
  24542. else {
  24543. // No cache for dynamic
  24544. for (var i = 0; i < size; i++) {
  24545. this._bufferData[location + i] = data[i];
  24546. }
  24547. }
  24548. };
  24549. // Update methods
  24550. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24551. // To match std140, matrix must be realigned
  24552. for (var i = 0; i < 3; i++) {
  24553. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24554. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24555. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24556. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24557. }
  24558. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24559. };
  24560. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24561. this._currentEffect.setMatrix3x3(name, matrix);
  24562. };
  24563. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24564. this._currentEffect.setMatrix2x2(name, matrix);
  24565. };
  24566. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24567. // To match std140, matrix must be realigned
  24568. for (var i = 0; i < 2; i++) {
  24569. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24570. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24571. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24572. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24573. }
  24574. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24575. };
  24576. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24577. this._currentEffect.setFloat(name, x);
  24578. };
  24579. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24580. UniformBuffer._tempBuffer[0] = x;
  24581. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24582. };
  24583. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24584. if (suffix === void 0) { suffix = ""; }
  24585. this._currentEffect.setFloat2(name + suffix, x, y);
  24586. };
  24587. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24588. if (suffix === void 0) { suffix = ""; }
  24589. UniformBuffer._tempBuffer[0] = x;
  24590. UniformBuffer._tempBuffer[1] = y;
  24591. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24592. };
  24593. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24594. if (suffix === void 0) { suffix = ""; }
  24595. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24596. };
  24597. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24598. if (suffix === void 0) { suffix = ""; }
  24599. UniformBuffer._tempBuffer[0] = x;
  24600. UniformBuffer._tempBuffer[1] = y;
  24601. UniformBuffer._tempBuffer[2] = z;
  24602. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24603. };
  24604. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24605. if (suffix === void 0) { suffix = ""; }
  24606. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24607. };
  24608. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24609. if (suffix === void 0) { suffix = ""; }
  24610. UniformBuffer._tempBuffer[0] = x;
  24611. UniformBuffer._tempBuffer[1] = y;
  24612. UniformBuffer._tempBuffer[2] = z;
  24613. UniformBuffer._tempBuffer[3] = w;
  24614. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24615. };
  24616. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24617. this._currentEffect.setMatrix(name, mat);
  24618. };
  24619. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24620. this.updateUniform(name, mat.toArray(), 16);
  24621. };
  24622. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24623. this._currentEffect.setVector3(name, vector);
  24624. };
  24625. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24626. vector.toArray(UniformBuffer._tempBuffer);
  24627. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24628. };
  24629. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24630. this._currentEffect.setVector4(name, vector);
  24631. };
  24632. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24633. vector.toArray(UniformBuffer._tempBuffer);
  24634. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24635. };
  24636. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24637. if (suffix === void 0) { suffix = ""; }
  24638. this._currentEffect.setColor3(name + suffix, color);
  24639. };
  24640. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24641. if (suffix === void 0) { suffix = ""; }
  24642. color.toArray(UniformBuffer._tempBuffer);
  24643. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24644. };
  24645. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24646. if (suffix === void 0) { suffix = ""; }
  24647. this._currentEffect.setColor4(name + suffix, color, alpha);
  24648. };
  24649. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24650. if (suffix === void 0) { suffix = ""; }
  24651. color.toArray(UniformBuffer._tempBuffer);
  24652. UniformBuffer._tempBuffer[3] = alpha;
  24653. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24654. };
  24655. /**
  24656. * Sets a sampler uniform on the effect.
  24657. * @param {string} name Name of the sampler.
  24658. * @param {Texture} texture
  24659. */
  24660. UniformBuffer.prototype.setTexture = function (name, texture) {
  24661. this._currentEffect.setTexture(name, texture);
  24662. };
  24663. /**
  24664. * Directly updates the value of the uniform in the cache AND on the GPU.
  24665. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24666. * @param {number[]|Float32Array} data Flattened data
  24667. */
  24668. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24669. this.updateUniform(uniformName, data, data.length);
  24670. this.update();
  24671. };
  24672. /**
  24673. * Binds this uniform buffer to an effect.
  24674. * @param {Effect} effect
  24675. * @param {string} name Name of the uniform block in the shader.
  24676. */
  24677. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24678. this._currentEffect = effect;
  24679. if (this._noUBO) {
  24680. return;
  24681. }
  24682. effect.bindUniformBuffer(this._buffer, name);
  24683. };
  24684. /**
  24685. * Disposes the uniform buffer.
  24686. */
  24687. UniformBuffer.prototype.dispose = function () {
  24688. if (!this._buffer) {
  24689. return;
  24690. }
  24691. if (this._engine._releaseBuffer(this._buffer)) {
  24692. this._buffer = null;
  24693. }
  24694. };
  24695. return UniformBuffer;
  24696. }());
  24697. // Pool for avoiding memory leaks
  24698. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24699. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24700. BABYLON.UniformBuffer = UniformBuffer;
  24701. })(BABYLON || (BABYLON = {}));
  24702. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24703. var BABYLON;
  24704. (function (BABYLON) {
  24705. var PushMaterial = (function (_super) {
  24706. __extends(PushMaterial, _super);
  24707. function PushMaterial(name, scene) {
  24708. var _this = _super.call(this, name, scene) || this;
  24709. _this.storeEffectOnSubMeshes = true;
  24710. return _this;
  24711. }
  24712. PushMaterial.prototype.getEffect = function () {
  24713. return this._activeEffect;
  24714. };
  24715. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24716. if (!mesh) {
  24717. return false;
  24718. }
  24719. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24720. return true;
  24721. }
  24722. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24723. };
  24724. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24725. this._activeEffect.setMatrix("world", world);
  24726. };
  24727. PushMaterial.prototype.bind = function (world, mesh) {
  24728. if (!mesh) {
  24729. return;
  24730. }
  24731. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24732. };
  24733. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24734. _super.prototype._afterBind.call(this, mesh);
  24735. this.getScene()._cachedEffect = effect;
  24736. };
  24737. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24738. if (visibility === void 0) { visibility = 0; }
  24739. return scene.isCachedMaterialValid(this, effect, visibility);
  24740. };
  24741. return PushMaterial;
  24742. }(BABYLON.Material));
  24743. BABYLON.PushMaterial = PushMaterial;
  24744. })(BABYLON || (BABYLON = {}));
  24745. //# sourceMappingURL=babylon.pushMaterial.js.map
  24746. var BABYLON;
  24747. (function (BABYLON) {
  24748. var VertexData = (function () {
  24749. function VertexData() {
  24750. }
  24751. VertexData.prototype.set = function (data, kind) {
  24752. switch (kind) {
  24753. case BABYLON.VertexBuffer.PositionKind:
  24754. this.positions = data;
  24755. break;
  24756. case BABYLON.VertexBuffer.NormalKind:
  24757. this.normals = data;
  24758. break;
  24759. case BABYLON.VertexBuffer.TangentKind:
  24760. this.tangents = data;
  24761. break;
  24762. case BABYLON.VertexBuffer.UVKind:
  24763. this.uvs = data;
  24764. break;
  24765. case BABYLON.VertexBuffer.UV2Kind:
  24766. this.uvs2 = data;
  24767. break;
  24768. case BABYLON.VertexBuffer.UV3Kind:
  24769. this.uvs3 = data;
  24770. break;
  24771. case BABYLON.VertexBuffer.UV4Kind:
  24772. this.uvs4 = data;
  24773. break;
  24774. case BABYLON.VertexBuffer.UV5Kind:
  24775. this.uvs5 = data;
  24776. break;
  24777. case BABYLON.VertexBuffer.UV6Kind:
  24778. this.uvs6 = data;
  24779. break;
  24780. case BABYLON.VertexBuffer.ColorKind:
  24781. this.colors = data;
  24782. break;
  24783. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24784. this.matricesIndices = data;
  24785. break;
  24786. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24787. this.matricesWeights = data;
  24788. break;
  24789. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24790. this.matricesIndicesExtra = data;
  24791. break;
  24792. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24793. this.matricesWeightsExtra = data;
  24794. break;
  24795. }
  24796. };
  24797. /**
  24798. * Associates the vertexData to the passed Mesh.
  24799. * Sets it as updatable or not (default `false`).
  24800. * Returns the VertexData.
  24801. */
  24802. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24803. this._applyTo(mesh, updatable);
  24804. return this;
  24805. };
  24806. /**
  24807. * Associates the vertexData to the passed Geometry.
  24808. * Sets it as updatable or not (default `false`).
  24809. * Returns the VertexData.
  24810. */
  24811. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24812. this._applyTo(geometry, updatable);
  24813. return this;
  24814. };
  24815. /**
  24816. * Updates the associated mesh.
  24817. * Returns the VertexData.
  24818. */
  24819. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24820. this._update(mesh);
  24821. return this;
  24822. };
  24823. /**
  24824. * Updates the associated geometry.
  24825. * Returns the VertexData.
  24826. */
  24827. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24828. this._update(geometry);
  24829. return this;
  24830. };
  24831. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24832. if (this.positions) {
  24833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24834. }
  24835. if (this.normals) {
  24836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24837. }
  24838. if (this.tangents) {
  24839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24840. }
  24841. if (this.uvs) {
  24842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24843. }
  24844. if (this.uvs2) {
  24845. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24846. }
  24847. if (this.uvs3) {
  24848. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24849. }
  24850. if (this.uvs4) {
  24851. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24852. }
  24853. if (this.uvs5) {
  24854. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24855. }
  24856. if (this.uvs6) {
  24857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24858. }
  24859. if (this.colors) {
  24860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24861. }
  24862. if (this.matricesIndices) {
  24863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24864. }
  24865. if (this.matricesWeights) {
  24866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24867. }
  24868. if (this.matricesIndicesExtra) {
  24869. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24870. }
  24871. if (this.matricesWeightsExtra) {
  24872. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24873. }
  24874. if (this.indices) {
  24875. meshOrGeometry.setIndices(this.indices);
  24876. }
  24877. return this;
  24878. };
  24879. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24880. if (this.positions) {
  24881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24882. }
  24883. if (this.normals) {
  24884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24885. }
  24886. if (this.tangents) {
  24887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24888. }
  24889. if (this.uvs) {
  24890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24891. }
  24892. if (this.uvs2) {
  24893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24894. }
  24895. if (this.uvs3) {
  24896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24897. }
  24898. if (this.uvs4) {
  24899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24900. }
  24901. if (this.uvs5) {
  24902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24903. }
  24904. if (this.uvs6) {
  24905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24906. }
  24907. if (this.colors) {
  24908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24909. }
  24910. if (this.matricesIndices) {
  24911. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24912. }
  24913. if (this.matricesWeights) {
  24914. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24915. }
  24916. if (this.matricesIndicesExtra) {
  24917. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24918. }
  24919. if (this.matricesWeightsExtra) {
  24920. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24921. }
  24922. if (this.indices) {
  24923. meshOrGeometry.setIndices(this.indices);
  24924. }
  24925. return this;
  24926. };
  24927. /**
  24928. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24929. * Returns the VertexData.
  24930. */
  24931. VertexData.prototype.transform = function (matrix) {
  24932. var transformed = BABYLON.Vector3.Zero();
  24933. var index;
  24934. if (this.positions) {
  24935. var position = BABYLON.Vector3.Zero();
  24936. for (index = 0; index < this.positions.length; index += 3) {
  24937. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24938. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24939. this.positions[index] = transformed.x;
  24940. this.positions[index + 1] = transformed.y;
  24941. this.positions[index + 2] = transformed.z;
  24942. }
  24943. }
  24944. if (this.normals) {
  24945. var normal = BABYLON.Vector3.Zero();
  24946. for (index = 0; index < this.normals.length; index += 3) {
  24947. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24948. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24949. this.normals[index] = transformed.x;
  24950. this.normals[index + 1] = transformed.y;
  24951. this.normals[index + 2] = transformed.z;
  24952. }
  24953. }
  24954. if (this.tangents) {
  24955. var tangent = BABYLON.Vector4.Zero();
  24956. var tangentTransformed = BABYLON.Vector4.Zero();
  24957. for (index = 0; index < this.tangents.length; index += 4) {
  24958. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24959. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24960. this.tangents[index] = tangentTransformed.x;
  24961. this.tangents[index + 1] = tangentTransformed.y;
  24962. this.tangents[index + 2] = tangentTransformed.z;
  24963. this.tangents[index + 3] = tangentTransformed.w;
  24964. }
  24965. }
  24966. return this;
  24967. };
  24968. /**
  24969. * Merges the passed VertexData into the current one.
  24970. * Returns the modified VertexData.
  24971. */
  24972. VertexData.prototype.merge = function (other) {
  24973. if (other.indices) {
  24974. if (!this.indices) {
  24975. this.indices = [];
  24976. }
  24977. var offset = this.positions ? this.positions.length / 3 : 0;
  24978. for (var index = 0; index < other.indices.length; index++) {
  24979. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24980. this.indices.push(other.indices[index] + offset);
  24981. }
  24982. }
  24983. this.positions = this._mergeElement(this.positions, other.positions);
  24984. this.normals = this._mergeElement(this.normals, other.normals);
  24985. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24986. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24987. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24988. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24989. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24990. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24991. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24992. this.colors = this._mergeElement(this.colors, other.colors);
  24993. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24994. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24995. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24996. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24997. return this;
  24998. };
  24999. VertexData.prototype._mergeElement = function (source, other) {
  25000. if (!other)
  25001. return source;
  25002. if (!source)
  25003. return other;
  25004. var len = other.length + source.length;
  25005. var isSrcTypedArray = source instanceof Float32Array;
  25006. var isOthTypedArray = other instanceof Float32Array;
  25007. // use non-loop method when the source is Float32Array
  25008. if (isSrcTypedArray) {
  25009. var ret32 = new Float32Array(len);
  25010. ret32.set(source);
  25011. ret32.set(other, source.length);
  25012. return ret32;
  25013. // source is number[], when other is also use concat
  25014. }
  25015. else if (!isOthTypedArray) {
  25016. return source.concat(other);
  25017. // source is a number[], but other is a Float32Array, loop required
  25018. }
  25019. else {
  25020. var ret = source.slice(0); // copy source to a separate array
  25021. for (var i = 0, len = other.length; i < len; i++) {
  25022. ret.push(other[i]);
  25023. }
  25024. return ret;
  25025. }
  25026. };
  25027. /**
  25028. * Serializes the VertexData.
  25029. * Returns a serialized object.
  25030. */
  25031. VertexData.prototype.serialize = function () {
  25032. var serializationObject = this.serialize();
  25033. if (this.positions) {
  25034. serializationObject.positions = this.positions;
  25035. }
  25036. if (this.normals) {
  25037. serializationObject.normals = this.normals;
  25038. }
  25039. if (this.tangents) {
  25040. serializationObject.tangents = this.tangents;
  25041. }
  25042. if (this.uvs) {
  25043. serializationObject.uvs = this.uvs;
  25044. }
  25045. if (this.uvs2) {
  25046. serializationObject.uvs2 = this.uvs2;
  25047. }
  25048. if (this.uvs3) {
  25049. serializationObject.uvs3 = this.uvs3;
  25050. }
  25051. if (this.uvs4) {
  25052. serializationObject.uvs4 = this.uvs4;
  25053. }
  25054. if (this.uvs5) {
  25055. serializationObject.uvs5 = this.uvs5;
  25056. }
  25057. if (this.uvs6) {
  25058. serializationObject.uvs6 = this.uvs6;
  25059. }
  25060. if (this.colors) {
  25061. serializationObject.colors = this.colors;
  25062. }
  25063. if (this.matricesIndices) {
  25064. serializationObject.matricesIndices = this.matricesIndices;
  25065. serializationObject.matricesIndices._isExpanded = true;
  25066. }
  25067. if (this.matricesWeights) {
  25068. serializationObject.matricesWeights = this.matricesWeights;
  25069. }
  25070. if (this.matricesIndicesExtra) {
  25071. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25072. serializationObject.matricesIndicesExtra._isExpanded = true;
  25073. }
  25074. if (this.matricesWeightsExtra) {
  25075. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25076. }
  25077. serializationObject.indices = this.indices;
  25078. return serializationObject;
  25079. };
  25080. // Statics
  25081. /**
  25082. * Returns the object VertexData associated to the passed mesh.
  25083. */
  25084. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25085. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25086. };
  25087. /**
  25088. * Returns the object VertexData associated to the passed geometry.
  25089. */
  25090. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25091. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25092. };
  25093. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25094. var result = new VertexData();
  25095. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25096. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25097. }
  25098. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25099. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25100. }
  25101. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25102. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25103. }
  25104. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25105. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25106. }
  25107. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25108. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25109. }
  25110. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25111. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25112. }
  25113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25114. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25115. }
  25116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25117. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25118. }
  25119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25120. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25121. }
  25122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25123. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25124. }
  25125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25126. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25127. }
  25128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25129. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25130. }
  25131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25132. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25133. }
  25134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25135. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25136. }
  25137. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25138. return result;
  25139. };
  25140. /**
  25141. * Creates the vertexData of the Ribbon.
  25142. */
  25143. VertexData.CreateRibbon = function (options) {
  25144. var pathArray = options.pathArray;
  25145. var closeArray = options.closeArray || false;
  25146. var closePath = options.closePath || false;
  25147. var invertUV = options.invertUV || false;
  25148. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25149. var offset = options.offset || defaultOffset;
  25150. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25151. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25152. var customUV = options.uvs;
  25153. var customColors = options.colors;
  25154. var positions = [];
  25155. var indices = [];
  25156. var normals = [];
  25157. var uvs = [];
  25158. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25159. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25160. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25161. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25162. var minlg; // minimal length among all paths from pathArray
  25163. var lg = []; // array of path lengths : nb of vertex per path
  25164. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25165. var p; // path iterator
  25166. var i; // point iterator
  25167. var j; // point iterator
  25168. // if single path in pathArray
  25169. if (pathArray.length < 2) {
  25170. var ar1 = [];
  25171. var ar2 = [];
  25172. for (i = 0; i < pathArray[0].length - offset; i++) {
  25173. ar1.push(pathArray[0][i]);
  25174. ar2.push(pathArray[0][i + offset]);
  25175. }
  25176. pathArray = [ar1, ar2];
  25177. }
  25178. // positions and horizontal distances (u)
  25179. var idc = 0;
  25180. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25181. var path;
  25182. var l;
  25183. minlg = pathArray[0].length;
  25184. var vectlg;
  25185. var dist;
  25186. for (p = 0; p < pathArray.length; p++) {
  25187. uTotalDistance[p] = 0;
  25188. us[p] = [0];
  25189. path = pathArray[p];
  25190. l = path.length;
  25191. minlg = (minlg < l) ? minlg : l;
  25192. j = 0;
  25193. while (j < l) {
  25194. positions.push(path[j].x, path[j].y, path[j].z);
  25195. if (j > 0) {
  25196. vectlg = path[j].subtract(path[j - 1]).length();
  25197. dist = vectlg + uTotalDistance[p];
  25198. us[p].push(dist);
  25199. uTotalDistance[p] = dist;
  25200. }
  25201. j++;
  25202. }
  25203. if (closePath) {
  25204. j--;
  25205. positions.push(path[0].x, path[0].y, path[0].z);
  25206. vectlg = path[j].subtract(path[0]).length();
  25207. dist = vectlg + uTotalDistance[p];
  25208. us[p].push(dist);
  25209. uTotalDistance[p] = dist;
  25210. }
  25211. lg[p] = l + closePathCorr;
  25212. idx[p] = idc;
  25213. idc += (l + closePathCorr);
  25214. }
  25215. // vertical distances (v)
  25216. var path1;
  25217. var path2;
  25218. var vertex1;
  25219. var vertex2;
  25220. for (i = 0; i < minlg + closePathCorr; i++) {
  25221. vTotalDistance[i] = 0;
  25222. vs[i] = [0];
  25223. for (p = 0; p < pathArray.length - 1; p++) {
  25224. path1 = pathArray[p];
  25225. path2 = pathArray[p + 1];
  25226. if (i === minlg) {
  25227. vertex1 = path1[0];
  25228. vertex2 = path2[0];
  25229. }
  25230. else {
  25231. vertex1 = path1[i];
  25232. vertex2 = path2[i];
  25233. }
  25234. vectlg = vertex2.subtract(vertex1).length();
  25235. dist = vectlg + vTotalDistance[i];
  25236. vs[i].push(dist);
  25237. vTotalDistance[i] = dist;
  25238. }
  25239. if (closeArray) {
  25240. path1 = pathArray[p];
  25241. path2 = pathArray[0];
  25242. if (i === minlg) {
  25243. vertex2 = path2[0];
  25244. }
  25245. vectlg = vertex2.subtract(vertex1).length();
  25246. dist = vectlg + vTotalDistance[i];
  25247. vTotalDistance[i] = dist;
  25248. }
  25249. }
  25250. // uvs
  25251. var u;
  25252. var v;
  25253. if (customUV) {
  25254. for (p = 0; p < customUV.length; p++) {
  25255. uvs.push(customUV[p].x, customUV[p].y);
  25256. }
  25257. }
  25258. else {
  25259. for (p = 0; p < pathArray.length; p++) {
  25260. for (i = 0; i < minlg + closePathCorr; i++) {
  25261. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25262. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25263. if (invertUV) {
  25264. uvs.push(v, u);
  25265. }
  25266. else {
  25267. uvs.push(u, v);
  25268. }
  25269. }
  25270. }
  25271. }
  25272. // indices
  25273. p = 0; // path index
  25274. var pi = 0; // positions array index
  25275. var l1 = lg[p] - 1; // path1 length
  25276. var l2 = lg[p + 1] - 1; // path2 length
  25277. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25278. var shft = idx[1] - idx[0]; // shift
  25279. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25280. while (pi <= min && p < path1nb) {
  25281. // 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
  25282. indices.push(pi, pi + shft, pi + 1);
  25283. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25284. pi += 1;
  25285. if (pi === min) {
  25286. p++;
  25287. if (p === lg.length - 1) {
  25288. shft = idx[0] - idx[p];
  25289. l1 = lg[p] - 1;
  25290. l2 = lg[0] - 1;
  25291. }
  25292. else {
  25293. shft = idx[p + 1] - idx[p];
  25294. l1 = lg[p] - 1;
  25295. l2 = lg[p + 1] - 1;
  25296. }
  25297. pi = idx[p];
  25298. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25299. }
  25300. }
  25301. // normals
  25302. VertexData.ComputeNormals(positions, indices, normals);
  25303. if (closePath) {
  25304. var indexFirst = 0;
  25305. var indexLast = 0;
  25306. for (p = 0; p < pathArray.length; p++) {
  25307. indexFirst = idx[p] * 3;
  25308. if (p + 1 < pathArray.length) {
  25309. indexLast = (idx[p + 1] - 1) * 3;
  25310. }
  25311. else {
  25312. indexLast = normals.length - 3;
  25313. }
  25314. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25315. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25316. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25317. normals[indexLast] = normals[indexFirst];
  25318. normals[indexLast + 1] = normals[indexFirst + 1];
  25319. normals[indexLast + 2] = normals[indexFirst + 2];
  25320. }
  25321. }
  25322. // sides
  25323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25324. // Colors
  25325. if (customColors) {
  25326. var colors = new Float32Array(customColors.length * 4);
  25327. for (var c = 0; c < customColors.length; c++) {
  25328. colors[c * 4] = customColors[c].r;
  25329. colors[c * 4 + 1] = customColors[c].g;
  25330. colors[c * 4 + 2] = customColors[c].b;
  25331. colors[c * 4 + 3] = customColors[c].a;
  25332. }
  25333. }
  25334. // Result
  25335. var vertexData = new VertexData();
  25336. var positions32 = new Float32Array(positions);
  25337. var normals32 = new Float32Array(normals);
  25338. var uvs32 = new Float32Array(uvs);
  25339. vertexData.indices = indices;
  25340. vertexData.positions = positions32;
  25341. vertexData.normals = normals32;
  25342. vertexData.uvs = uvs32;
  25343. if (customColors) {
  25344. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25345. }
  25346. if (closePath) {
  25347. vertexData._idx = idx;
  25348. }
  25349. return vertexData;
  25350. };
  25351. /**
  25352. * Creates the VertexData of the Box.
  25353. */
  25354. VertexData.CreateBox = function (options) {
  25355. var normalsSource = [
  25356. new BABYLON.Vector3(0, 0, 1),
  25357. new BABYLON.Vector3(0, 0, -1),
  25358. new BABYLON.Vector3(1, 0, 0),
  25359. new BABYLON.Vector3(-1, 0, 0),
  25360. new BABYLON.Vector3(0, 1, 0),
  25361. new BABYLON.Vector3(0, -1, 0)
  25362. ];
  25363. var indices = [];
  25364. var positions = [];
  25365. var normals = [];
  25366. var uvs = [];
  25367. var width = options.width || options.size || 1;
  25368. var height = options.height || options.size || 1;
  25369. var depth = options.depth || options.size || 1;
  25370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25371. var faceUV = options.faceUV || new Array(6);
  25372. var faceColors = options.faceColors;
  25373. var colors = [];
  25374. // default face colors and UV if undefined
  25375. for (var f = 0; f < 6; f++) {
  25376. if (faceUV[f] === undefined) {
  25377. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25378. }
  25379. if (faceColors && faceColors[f] === undefined) {
  25380. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25381. }
  25382. }
  25383. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25384. // Create each face in turn.
  25385. for (var index = 0; index < normalsSource.length; index++) {
  25386. var normal = normalsSource[index];
  25387. // Get two vectors perpendicular to the face normal and to each other.
  25388. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25389. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25390. // Six indices (two triangles) per face.
  25391. var verticesLength = positions.length / 3;
  25392. indices.push(verticesLength);
  25393. indices.push(verticesLength + 1);
  25394. indices.push(verticesLength + 2);
  25395. indices.push(verticesLength);
  25396. indices.push(verticesLength + 2);
  25397. indices.push(verticesLength + 3);
  25398. // Four vertices per face.
  25399. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25400. positions.push(vertex.x, vertex.y, vertex.z);
  25401. normals.push(normal.x, normal.y, normal.z);
  25402. uvs.push(faceUV[index].z, faceUV[index].w);
  25403. if (faceColors) {
  25404. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25405. }
  25406. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25407. positions.push(vertex.x, vertex.y, vertex.z);
  25408. normals.push(normal.x, normal.y, normal.z);
  25409. uvs.push(faceUV[index].x, faceUV[index].w);
  25410. if (faceColors) {
  25411. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25412. }
  25413. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25414. positions.push(vertex.x, vertex.y, vertex.z);
  25415. normals.push(normal.x, normal.y, normal.z);
  25416. uvs.push(faceUV[index].x, faceUV[index].y);
  25417. if (faceColors) {
  25418. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25419. }
  25420. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25421. positions.push(vertex.x, vertex.y, vertex.z);
  25422. normals.push(normal.x, normal.y, normal.z);
  25423. uvs.push(faceUV[index].z, faceUV[index].y);
  25424. if (faceColors) {
  25425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25426. }
  25427. }
  25428. // sides
  25429. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25430. // Result
  25431. var vertexData = new VertexData();
  25432. vertexData.indices = indices;
  25433. vertexData.positions = positions;
  25434. vertexData.normals = normals;
  25435. vertexData.uvs = uvs;
  25436. if (faceColors) {
  25437. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25438. vertexData.colors = totalColors;
  25439. }
  25440. return vertexData;
  25441. };
  25442. /**
  25443. * Creates the VertexData of the Sphere.
  25444. */
  25445. VertexData.CreateSphere = function (options) {
  25446. var segments = options.segments || 32;
  25447. var diameterX = options.diameterX || options.diameter || 1;
  25448. var diameterY = options.diameterY || options.diameter || 1;
  25449. var diameterZ = options.diameterZ || options.diameter || 1;
  25450. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25451. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25452. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25453. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25454. var totalZRotationSteps = 2 + segments;
  25455. var totalYRotationSteps = 2 * totalZRotationSteps;
  25456. var indices = [];
  25457. var positions = [];
  25458. var normals = [];
  25459. var uvs = [];
  25460. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25461. var normalizedZ = zRotationStep / totalZRotationSteps;
  25462. var angleZ = normalizedZ * Math.PI * slice;
  25463. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25464. var normalizedY = yRotationStep / totalYRotationSteps;
  25465. var angleY = normalizedY * Math.PI * 2 * arc;
  25466. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25467. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25468. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25469. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25470. var vertex = complete.multiply(radius);
  25471. var normal = complete.divide(radius).normalize();
  25472. positions.push(vertex.x, vertex.y, vertex.z);
  25473. normals.push(normal.x, normal.y, normal.z);
  25474. uvs.push(normalizedY, normalizedZ);
  25475. }
  25476. if (zRotationStep > 0) {
  25477. var verticesCount = positions.length / 3;
  25478. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25479. indices.push((firstIndex));
  25480. indices.push((firstIndex + 1));
  25481. indices.push(firstIndex + totalYRotationSteps + 1);
  25482. indices.push((firstIndex + totalYRotationSteps + 1));
  25483. indices.push((firstIndex + 1));
  25484. indices.push((firstIndex + totalYRotationSteps + 2));
  25485. }
  25486. }
  25487. }
  25488. // Sides
  25489. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25490. // Result
  25491. var vertexData = new VertexData();
  25492. vertexData.indices = indices;
  25493. vertexData.positions = positions;
  25494. vertexData.normals = normals;
  25495. vertexData.uvs = uvs;
  25496. return vertexData;
  25497. };
  25498. /**
  25499. * Creates the VertexData of the Cylinder or Cone.
  25500. */
  25501. VertexData.CreateCylinder = function (options) {
  25502. var height = options.height || 2;
  25503. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25504. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25505. var tessellation = options.tessellation || 24;
  25506. var subdivisions = options.subdivisions || 1;
  25507. var hasRings = options.hasRings;
  25508. var enclose = options.enclose;
  25509. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25510. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25511. var faceUV = options.faceUV || new Array(3);
  25512. var faceColors = options.faceColors;
  25513. // default face colors and UV if undefined
  25514. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25515. var ringNb = (hasRings) ? subdivisions : 1;
  25516. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25517. var f;
  25518. for (f = 0; f < surfaceNb; f++) {
  25519. if (faceColors && faceColors[f] === undefined) {
  25520. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25521. }
  25522. }
  25523. for (f = 0; f < surfaceNb; f++) {
  25524. if (faceUV && faceUV[f] === undefined) {
  25525. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25526. }
  25527. }
  25528. var indices = [];
  25529. var positions = [];
  25530. var normals = [];
  25531. var uvs = [];
  25532. var colors = [];
  25533. var angle_step = Math.PI * 2 * arc / tessellation;
  25534. var angle;
  25535. var h;
  25536. var radius;
  25537. var tan = (diameterBottom - diameterTop) / 2 / height;
  25538. var ringVertex = BABYLON.Vector3.Zero();
  25539. var ringNormal = BABYLON.Vector3.Zero();
  25540. var ringFirstVertex = BABYLON.Vector3.Zero();
  25541. var ringFirstNormal = BABYLON.Vector3.Zero();
  25542. var quadNormal = BABYLON.Vector3.Zero();
  25543. var Y = BABYLON.Axis.Y;
  25544. // positions, normals, uvs
  25545. var i;
  25546. var j;
  25547. var r;
  25548. var ringIdx = 1;
  25549. var s = 1; // surface index
  25550. var cs = 0;
  25551. var v = 0;
  25552. for (i = 0; i <= subdivisions; i++) {
  25553. h = i / subdivisions;
  25554. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25555. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25556. for (r = 0; r < ringIdx; r++) {
  25557. if (hasRings) {
  25558. s += r;
  25559. }
  25560. if (enclose) {
  25561. s += 2 * r;
  25562. }
  25563. for (j = 0; j <= tessellation; j++) {
  25564. angle = j * angle_step;
  25565. // position
  25566. ringVertex.x = Math.cos(-angle) * radius;
  25567. ringVertex.y = -height / 2 + h * height;
  25568. ringVertex.z = Math.sin(-angle) * radius;
  25569. // normal
  25570. if (diameterTop === 0 && i === subdivisions) {
  25571. // if no top cap, reuse former normals
  25572. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25573. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25574. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25575. }
  25576. else {
  25577. ringNormal.x = ringVertex.x;
  25578. ringNormal.z = ringVertex.z;
  25579. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25580. ringNormal.normalize();
  25581. }
  25582. // keep first ring vertex values for enclose
  25583. if (j === 0) {
  25584. ringFirstVertex.copyFrom(ringVertex);
  25585. ringFirstNormal.copyFrom(ringNormal);
  25586. }
  25587. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25588. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25589. if (hasRings) {
  25590. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25591. }
  25592. else {
  25593. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25594. }
  25595. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25596. if (faceColors) {
  25597. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25598. }
  25599. }
  25600. // if enclose, add four vertices and their dedicated normals
  25601. if (arc !== 1 && enclose) {
  25602. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25603. positions.push(0, ringVertex.y, 0);
  25604. positions.push(0, ringVertex.y, 0);
  25605. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25606. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25607. quadNormal.normalize();
  25608. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25609. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25610. quadNormal.normalize();
  25611. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25612. if (hasRings) {
  25613. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25614. }
  25615. else {
  25616. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25617. }
  25618. uvs.push(faceUV[s + 1].x, v);
  25619. uvs.push(faceUV[s + 1].z, v);
  25620. if (hasRings) {
  25621. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25622. }
  25623. else {
  25624. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25625. }
  25626. uvs.push(faceUV[s + 2].x, v);
  25627. uvs.push(faceUV[s + 2].z, v);
  25628. if (faceColors) {
  25629. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25630. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25631. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25632. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25633. }
  25634. }
  25635. if (cs !== s) {
  25636. cs = s;
  25637. }
  25638. }
  25639. }
  25640. // indices
  25641. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25642. var s;
  25643. i = 0;
  25644. for (s = 0; s < subdivisions; s++) {
  25645. for (j = 0; j < tessellation; j++) {
  25646. var i0 = i * (e + 1) + j;
  25647. var i1 = (i + 1) * (e + 1) + j;
  25648. var i2 = i * (e + 1) + (j + 1);
  25649. var i3 = (i + 1) * (e + 1) + (j + 1);
  25650. indices.push(i0, i1, i2);
  25651. indices.push(i3, i2, i1);
  25652. }
  25653. if (arc !== 1 && enclose) {
  25654. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25655. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25656. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25657. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25658. }
  25659. i = (hasRings) ? (i + 2) : (i + 1);
  25660. }
  25661. // Caps
  25662. var createCylinderCap = function (isTop) {
  25663. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25664. if (radius === 0) {
  25665. return;
  25666. }
  25667. // Cap positions, normals & uvs
  25668. var angle;
  25669. var circleVector;
  25670. var i;
  25671. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25672. var c;
  25673. if (faceColors) {
  25674. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25675. }
  25676. // cap center
  25677. var vbase = positions.length / 3;
  25678. var offset = isTop ? height / 2 : -height / 2;
  25679. var center = new BABYLON.Vector3(0, offset, 0);
  25680. positions.push(center.x, center.y, center.z);
  25681. normals.push(0, isTop ? 1 : -1, 0);
  25682. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25683. if (faceColors) {
  25684. colors.push(c.r, c.g, c.b, c.a);
  25685. }
  25686. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25687. for (i = 0; i <= tessellation; i++) {
  25688. angle = Math.PI * 2 * i * arc / tessellation;
  25689. var cos = Math.cos(-angle);
  25690. var sin = Math.sin(-angle);
  25691. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25692. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25693. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25694. normals.push(0, isTop ? 1 : -1, 0);
  25695. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25696. if (faceColors) {
  25697. colors.push(c.r, c.g, c.b, c.a);
  25698. }
  25699. }
  25700. // Cap indices
  25701. for (i = 0; i < tessellation; i++) {
  25702. if (!isTop) {
  25703. indices.push(vbase);
  25704. indices.push(vbase + (i + 1));
  25705. indices.push(vbase + (i + 2));
  25706. }
  25707. else {
  25708. indices.push(vbase);
  25709. indices.push(vbase + (i + 2));
  25710. indices.push(vbase + (i + 1));
  25711. }
  25712. }
  25713. };
  25714. // add caps to geometry
  25715. createCylinderCap(false);
  25716. createCylinderCap(true);
  25717. // Sides
  25718. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25719. var vertexData = new VertexData();
  25720. vertexData.indices = indices;
  25721. vertexData.positions = positions;
  25722. vertexData.normals = normals;
  25723. vertexData.uvs = uvs;
  25724. if (faceColors) {
  25725. vertexData.colors = colors;
  25726. }
  25727. return vertexData;
  25728. };
  25729. /**
  25730. * Creates the VertexData of the Torus.
  25731. */
  25732. VertexData.CreateTorus = function (options) {
  25733. var indices = [];
  25734. var positions = [];
  25735. var normals = [];
  25736. var uvs = [];
  25737. var diameter = options.diameter || 1;
  25738. var thickness = options.thickness || 0.5;
  25739. var tessellation = options.tessellation || 16;
  25740. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25741. var stride = tessellation + 1;
  25742. for (var i = 0; i <= tessellation; i++) {
  25743. var u = i / tessellation;
  25744. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25745. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25746. for (var j = 0; j <= tessellation; j++) {
  25747. var v = 1 - j / tessellation;
  25748. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25749. var dx = Math.cos(innerAngle);
  25750. var dy = Math.sin(innerAngle);
  25751. // Create a vertex.
  25752. var normal = new BABYLON.Vector3(dx, dy, 0);
  25753. var position = normal.scale(thickness / 2);
  25754. var textureCoordinate = new BABYLON.Vector2(u, v);
  25755. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25756. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25757. positions.push(position.x, position.y, position.z);
  25758. normals.push(normal.x, normal.y, normal.z);
  25759. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25760. // And create indices for two triangles.
  25761. var nextI = (i + 1) % stride;
  25762. var nextJ = (j + 1) % stride;
  25763. indices.push(i * stride + j);
  25764. indices.push(i * stride + nextJ);
  25765. indices.push(nextI * stride + j);
  25766. indices.push(i * stride + nextJ);
  25767. indices.push(nextI * stride + nextJ);
  25768. indices.push(nextI * stride + j);
  25769. }
  25770. }
  25771. // Sides
  25772. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25773. // Result
  25774. var vertexData = new VertexData();
  25775. vertexData.indices = indices;
  25776. vertexData.positions = positions;
  25777. vertexData.normals = normals;
  25778. vertexData.uvs = uvs;
  25779. return vertexData;
  25780. };
  25781. /**
  25782. * Creates the VertexData of the LineSystem.
  25783. */
  25784. VertexData.CreateLineSystem = function (options) {
  25785. var indices = [];
  25786. var positions = [];
  25787. var lines = options.lines;
  25788. var idx = 0;
  25789. for (var l = 0; l < lines.length; l++) {
  25790. var points = lines[l];
  25791. for (var index = 0; index < points.length; index++) {
  25792. positions.push(points[index].x, points[index].y, points[index].z);
  25793. if (index > 0) {
  25794. indices.push(idx - 1);
  25795. indices.push(idx);
  25796. }
  25797. idx++;
  25798. }
  25799. }
  25800. var vertexData = new VertexData();
  25801. vertexData.indices = indices;
  25802. vertexData.positions = positions;
  25803. return vertexData;
  25804. };
  25805. /**
  25806. * Create the VertexData of the DashedLines.
  25807. */
  25808. VertexData.CreateDashedLines = function (options) {
  25809. var dashSize = options.dashSize || 3;
  25810. var gapSize = options.gapSize || 1;
  25811. var dashNb = options.dashNb || 200;
  25812. var points = options.points;
  25813. var positions = new Array();
  25814. var indices = new Array();
  25815. var curvect = BABYLON.Vector3.Zero();
  25816. var lg = 0;
  25817. var nb = 0;
  25818. var shft = 0;
  25819. var dashshft = 0;
  25820. var curshft = 0;
  25821. var idx = 0;
  25822. var i = 0;
  25823. for (i = 0; i < points.length - 1; i++) {
  25824. points[i + 1].subtractToRef(points[i], curvect);
  25825. lg += curvect.length();
  25826. }
  25827. shft = lg / dashNb;
  25828. dashshft = dashSize * shft / (dashSize + gapSize);
  25829. for (i = 0; i < points.length - 1; i++) {
  25830. points[i + 1].subtractToRef(points[i], curvect);
  25831. nb = Math.floor(curvect.length() / shft);
  25832. curvect.normalize();
  25833. for (var j = 0; j < nb; j++) {
  25834. curshft = shft * j;
  25835. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25836. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25837. indices.push(idx, idx + 1);
  25838. idx += 2;
  25839. }
  25840. }
  25841. // Result
  25842. var vertexData = new VertexData();
  25843. vertexData.positions = positions;
  25844. vertexData.indices = indices;
  25845. return vertexData;
  25846. };
  25847. /**
  25848. * Creates the VertexData of the Ground.
  25849. */
  25850. VertexData.CreateGround = function (options) {
  25851. var indices = [];
  25852. var positions = [];
  25853. var normals = [];
  25854. var uvs = [];
  25855. var row, col;
  25856. var width = options.width || 1;
  25857. var height = options.height || 1;
  25858. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25859. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25860. for (row = 0; row <= subdivisionsY; row++) {
  25861. for (col = 0; col <= subdivisionsX; col++) {
  25862. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25863. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25864. positions.push(position.x, position.y, position.z);
  25865. normals.push(normal.x, normal.y, normal.z);
  25866. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25867. }
  25868. }
  25869. for (row = 0; row < subdivisionsY; row++) {
  25870. for (col = 0; col < subdivisionsX; col++) {
  25871. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25872. indices.push(col + 1 + row * (subdivisionsX + 1));
  25873. indices.push(col + row * (subdivisionsX + 1));
  25874. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25875. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25876. indices.push(col + row * (subdivisionsX + 1));
  25877. }
  25878. }
  25879. // Result
  25880. var vertexData = new VertexData();
  25881. vertexData.indices = indices;
  25882. vertexData.positions = positions;
  25883. vertexData.normals = normals;
  25884. vertexData.uvs = uvs;
  25885. return vertexData;
  25886. };
  25887. /**
  25888. * Creates the VertexData of the TiledGround.
  25889. */
  25890. VertexData.CreateTiledGround = function (options) {
  25891. var xmin = options.xmin || -1.0;
  25892. var zmin = options.zmin || -1.0;
  25893. var xmax = options.xmax || 1.0;
  25894. var zmax = options.zmax || 1.0;
  25895. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25896. var precision = options.precision || { w: 1, h: 1 };
  25897. var indices = [];
  25898. var positions = [];
  25899. var normals = [];
  25900. var uvs = [];
  25901. var row, col, tileRow, tileCol;
  25902. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25903. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25904. precision.w = (precision.w < 1) ? 1 : precision.w;
  25905. precision.h = (precision.h < 1) ? 1 : precision.h;
  25906. var tileSize = {
  25907. 'w': (xmax - xmin) / subdivisions.w,
  25908. 'h': (zmax - zmin) / subdivisions.h
  25909. };
  25910. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25911. // Indices
  25912. var base = positions.length / 3;
  25913. var rowLength = precision.w + 1;
  25914. for (row = 0; row < precision.h; row++) {
  25915. for (col = 0; col < precision.w; col++) {
  25916. var square = [
  25917. base + col + row * rowLength,
  25918. base + (col + 1) + row * rowLength,
  25919. base + (col + 1) + (row + 1) * rowLength,
  25920. base + col + (row + 1) * rowLength
  25921. ];
  25922. indices.push(square[1]);
  25923. indices.push(square[2]);
  25924. indices.push(square[3]);
  25925. indices.push(square[0]);
  25926. indices.push(square[1]);
  25927. indices.push(square[3]);
  25928. }
  25929. }
  25930. // Position, normals and uvs
  25931. var position = BABYLON.Vector3.Zero();
  25932. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25933. for (row = 0; row <= precision.h; row++) {
  25934. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25935. for (col = 0; col <= precision.w; col++) {
  25936. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25937. position.y = 0;
  25938. positions.push(position.x, position.y, position.z);
  25939. normals.push(normal.x, normal.y, normal.z);
  25940. uvs.push(col / precision.w, row / precision.h);
  25941. }
  25942. }
  25943. }
  25944. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25945. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25946. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25947. }
  25948. }
  25949. // Result
  25950. var vertexData = new VertexData();
  25951. vertexData.indices = indices;
  25952. vertexData.positions = positions;
  25953. vertexData.normals = normals;
  25954. vertexData.uvs = uvs;
  25955. return vertexData;
  25956. };
  25957. /**
  25958. * Creates the VertexData of the Ground designed from a heightmap.
  25959. */
  25960. VertexData.CreateGroundFromHeightMap = function (options) {
  25961. var indices = [];
  25962. var positions = [];
  25963. var normals = [];
  25964. var uvs = [];
  25965. var row, col;
  25966. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25967. // Vertices
  25968. for (row = 0; row <= options.subdivisions; row++) {
  25969. for (col = 0; col <= options.subdivisions; col++) {
  25970. 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));
  25971. // Compute height
  25972. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25973. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25974. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25975. var r = options.buffer[pos] / 255.0;
  25976. var g = options.buffer[pos + 1] / 255.0;
  25977. var b = options.buffer[pos + 2] / 255.0;
  25978. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25979. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25980. // Add vertex
  25981. positions.push(position.x, position.y, position.z);
  25982. normals.push(0, 0, 0);
  25983. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25984. }
  25985. }
  25986. // Indices
  25987. for (row = 0; row < options.subdivisions; row++) {
  25988. for (col = 0; col < options.subdivisions; col++) {
  25989. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25990. indices.push(col + 1 + row * (options.subdivisions + 1));
  25991. indices.push(col + row * (options.subdivisions + 1));
  25992. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25993. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25994. indices.push(col + row * (options.subdivisions + 1));
  25995. }
  25996. }
  25997. // Normals
  25998. VertexData.ComputeNormals(positions, indices, normals);
  25999. // Result
  26000. var vertexData = new VertexData();
  26001. vertexData.indices = indices;
  26002. vertexData.positions = positions;
  26003. vertexData.normals = normals;
  26004. vertexData.uvs = uvs;
  26005. return vertexData;
  26006. };
  26007. /**
  26008. * Creates the VertexData of the Plane.
  26009. */
  26010. VertexData.CreatePlane = function (options) {
  26011. var indices = [];
  26012. var positions = [];
  26013. var normals = [];
  26014. var uvs = [];
  26015. var width = options.width || options.size || 1;
  26016. var height = options.height || options.size || 1;
  26017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26018. // Vertices
  26019. var halfWidth = width / 2.0;
  26020. var halfHeight = height / 2.0;
  26021. positions.push(-halfWidth, -halfHeight, 0);
  26022. normals.push(0, 0, -1.0);
  26023. uvs.push(0.0, 0.0);
  26024. positions.push(halfWidth, -halfHeight, 0);
  26025. normals.push(0, 0, -1.0);
  26026. uvs.push(1.0, 0.0);
  26027. positions.push(halfWidth, halfHeight, 0);
  26028. normals.push(0, 0, -1.0);
  26029. uvs.push(1.0, 1.0);
  26030. positions.push(-halfWidth, halfHeight, 0);
  26031. normals.push(0, 0, -1.0);
  26032. uvs.push(0.0, 1.0);
  26033. // Indices
  26034. indices.push(0);
  26035. indices.push(1);
  26036. indices.push(2);
  26037. indices.push(0);
  26038. indices.push(2);
  26039. indices.push(3);
  26040. // Sides
  26041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26042. // Result
  26043. var vertexData = new VertexData();
  26044. vertexData.indices = indices;
  26045. vertexData.positions = positions;
  26046. vertexData.normals = normals;
  26047. vertexData.uvs = uvs;
  26048. return vertexData;
  26049. };
  26050. /**
  26051. * Creates the VertexData of the Disc or regular Polygon.
  26052. */
  26053. VertexData.CreateDisc = function (options) {
  26054. var positions = [];
  26055. var indices = [];
  26056. var normals = [];
  26057. var uvs = [];
  26058. var radius = options.radius || 0.5;
  26059. var tessellation = options.tessellation || 64;
  26060. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26061. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26062. // positions and uvs
  26063. positions.push(0, 0, 0); // disc center first
  26064. uvs.push(0.5, 0.5);
  26065. var theta = Math.PI * 2 * arc;
  26066. var step = theta / tessellation;
  26067. for (var a = 0; a < theta; a += step) {
  26068. var x = Math.cos(a);
  26069. var y = Math.sin(a);
  26070. var u = (x + 1) / 2;
  26071. var v = (1 - y) / 2;
  26072. positions.push(radius * x, radius * y, 0);
  26073. uvs.push(u, v);
  26074. }
  26075. if (arc === 1) {
  26076. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26077. uvs.push(uvs[2], uvs[3]);
  26078. }
  26079. //indices
  26080. var vertexNb = positions.length / 3;
  26081. for (var i = 1; i < vertexNb - 1; i++) {
  26082. indices.push(i + 1, 0, i);
  26083. }
  26084. // result
  26085. VertexData.ComputeNormals(positions, indices, normals);
  26086. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26087. var vertexData = new VertexData();
  26088. vertexData.indices = indices;
  26089. vertexData.positions = positions;
  26090. vertexData.normals = normals;
  26091. vertexData.uvs = uvs;
  26092. return vertexData;
  26093. };
  26094. /**
  26095. * Re-creates the VertexData of the Polygon for sideOrientation.
  26096. */
  26097. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26098. var faceUV = fUV || new Array(3);
  26099. var faceColors = fColors;
  26100. var colors = [];
  26101. // default face colors and UV if undefined
  26102. for (var f = 0; f < 3; f++) {
  26103. if (faceUV[f] === undefined) {
  26104. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26105. }
  26106. if (faceColors && faceColors[f] === undefined) {
  26107. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26108. }
  26109. }
  26110. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26111. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26112. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26113. var indices = polygon.getIndices();
  26114. // set face colours and textures
  26115. var idx = 0;
  26116. var face = 0;
  26117. for (var index = 0; index < normals.length; index += 3) {
  26118. //Edge Face no. 1
  26119. if (Math.abs(normals[index + 1]) == 0) {
  26120. face = 1;
  26121. }
  26122. //Top Face no. 0
  26123. if (normals[index + 1] == 1) {
  26124. face = 0;
  26125. }
  26126. //Bottom Face no. 2
  26127. if (normals[index + 1] == -1) {
  26128. face = 2;
  26129. }
  26130. idx = index / 3;
  26131. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26132. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26133. if (faceColors) {
  26134. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26135. }
  26136. }
  26137. // sides
  26138. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26139. // Result
  26140. var vertexData = new VertexData();
  26141. vertexData.indices = indices;
  26142. vertexData.positions = positions;
  26143. vertexData.normals = normals;
  26144. vertexData.uvs = uvs;
  26145. if (faceColors) {
  26146. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26147. vertexData.colors = totalColors;
  26148. }
  26149. return vertexData;
  26150. };
  26151. /**
  26152. * Creates the VertexData of the IcoSphere.
  26153. */
  26154. VertexData.CreateIcoSphere = function (options) {
  26155. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26156. var radius = options.radius || 1;
  26157. var flat = (options.flat === undefined) ? true : options.flat;
  26158. var subdivisions = options.subdivisions || 4;
  26159. var radiusX = options.radiusX || radius;
  26160. var radiusY = options.radiusY || radius;
  26161. var radiusZ = options.radiusZ || radius;
  26162. var t = (1 + Math.sqrt(5)) / 2;
  26163. // 12 vertex x,y,z
  26164. var ico_vertices = [
  26165. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26166. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26167. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26168. ];
  26169. // index of 3 vertex makes a face of icopshere
  26170. var ico_indices = [
  26171. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26172. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26173. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26174. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26175. ];
  26176. // vertex for uv have aliased position, not for UV
  26177. var vertices_unalias_id = [
  26178. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26179. // vertex alias
  26180. 0,
  26181. 2,
  26182. 3,
  26183. 3,
  26184. 3,
  26185. 4,
  26186. 7,
  26187. 8,
  26188. 9,
  26189. 9,
  26190. 10,
  26191. 11 // 23: B + 12
  26192. ];
  26193. // uv as integer step (not pixels !)
  26194. var ico_vertexuv = [
  26195. 5, 1, 3, 1, 6, 4, 0, 0,
  26196. 5, 3, 4, 2, 2, 2, 4, 0,
  26197. 2, 0, 1, 1, 6, 0, 6, 2,
  26198. // vertex alias (for same vertex on different faces)
  26199. 0, 4,
  26200. 3, 3,
  26201. 4, 4,
  26202. 3, 1,
  26203. 4, 2,
  26204. 4, 4,
  26205. 0, 2,
  26206. 1, 1,
  26207. 2, 2,
  26208. 3, 3,
  26209. 1, 3,
  26210. 2, 4 // 23: B + 12
  26211. ];
  26212. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26213. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26214. // First island of uv mapping
  26215. // v = 4h 3+ 2
  26216. // v = 3h 9+ 4
  26217. // v = 2h 9+ 5 B
  26218. // v = 1h 9 1 0
  26219. // v = 0h 3 8 7 A
  26220. // u = 0 1 2 3 4 5 6 *a
  26221. // Second island of uv mapping
  26222. // v = 4h 0+ B+ 4+
  26223. // v = 3h A+ 2+
  26224. // v = 2h 7+ 6 3+
  26225. // v = 1h 8+ 3+
  26226. // v = 0h
  26227. // u = 0 1 2 3 4 5 6 *a
  26228. // Face layout on texture UV mapping
  26229. // ============
  26230. // \ 4 /\ 16 / ======
  26231. // \ / \ / /\ 11 /
  26232. // \/ 7 \/ / \ /
  26233. // ======= / 10 \/
  26234. // /\ 17 /\ =======
  26235. // / \ / \ \ 15 /\
  26236. // / 8 \/ 12 \ \ / \
  26237. // ============ \/ 6 \
  26238. // \ 18 /\ ============
  26239. // \ / \ \ 5 /\ 0 /
  26240. // \/ 13 \ \ / \ /
  26241. // ======= \/ 1 \/
  26242. // =============
  26243. // /\ 19 /\ 2 /\
  26244. // / \ / \ / \
  26245. // / 14 \/ 9 \/ 3 \
  26246. // ===================
  26247. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26248. var ustep = 138 / 1024;
  26249. var vstep = 239 / 1024;
  26250. var uoffset = 60 / 1024;
  26251. var voffset = 26 / 1024;
  26252. // Second island should have margin, not to touch the first island
  26253. // avoid any borderline artefact in pixel rounding
  26254. var island_u_offset = -40 / 1024;
  26255. var island_v_offset = +20 / 1024;
  26256. // face is either island 0 or 1 :
  26257. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26258. var island = [
  26259. 0, 0, 0, 0, 1,
  26260. 0, 0, 1, 1, 0,
  26261. 0, 0, 1, 1, 0,
  26262. 0, 1, 1, 1, 0 // 15 - 19
  26263. ];
  26264. var indices = [];
  26265. var positions = [];
  26266. var normals = [];
  26267. var uvs = [];
  26268. var current_indice = 0;
  26269. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26270. var face_vertex_pos = new Array(3);
  26271. var face_vertex_uv = new Array(3);
  26272. var v012;
  26273. for (v012 = 0; v012 < 3; v012++) {
  26274. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26275. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26276. }
  26277. // create all with normals
  26278. for (var face = 0; face < 20; face++) {
  26279. // 3 vertex per face
  26280. for (v012 = 0; v012 < 3; v012++) {
  26281. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26282. var v_id = ico_indices[3 * face + v012];
  26283. // vertex have 3D position (x,y,z)
  26284. 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]);
  26285. // Normalize to get normal, then scale to radius
  26286. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26287. // uv Coordinates from vertex ID
  26288. 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);
  26289. }
  26290. // Subdivide the face (interpolate pos, norm, uv)
  26291. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26292. // - norm is linear interpolation of vertex corner normal
  26293. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26294. // - uv is linear interpolation
  26295. //
  26296. // Topology is as below for sub-divide by 2
  26297. // vertex shown as v0,v1,v2
  26298. // interp index is i1 to progress in range [v0,v1[
  26299. // interp index is i2 to progress in range [v0,v2[
  26300. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26301. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26302. //
  26303. //
  26304. // i2 v2
  26305. // ^ ^
  26306. // / / \
  26307. // / / \
  26308. // / / \
  26309. // / / (0,1) \
  26310. // / #---------\
  26311. // / / \ (0,0)'/ \
  26312. // / / \ / \
  26313. // / / \ / \
  26314. // / / (0,0) \ / (1,0) \
  26315. // / #---------#---------\
  26316. // v0 v1
  26317. //
  26318. // --------------------> i1
  26319. //
  26320. // interp of (i1,i2):
  26321. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26322. // along i1 : lerp(x0,x1, i1/(S-i2))
  26323. //
  26324. // centroid of triangle is needed to get help normal computation
  26325. // (c1,c2) are used for centroid location
  26326. var interp_vertex = function (i1, i2, c1, c2) {
  26327. // vertex is interpolated from
  26328. // - face_vertex_pos[0..2]
  26329. // - face_vertex_uv[0..2]
  26330. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26331. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26332. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26333. pos_interp.normalize();
  26334. var vertex_normal;
  26335. if (flat) {
  26336. // in flat mode, recalculate normal as face centroid normal
  26337. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26338. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26339. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26340. }
  26341. else {
  26342. // in smooth mode, recalculate normal from each single vertex position
  26343. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26344. }
  26345. // Vertex normal need correction due to X,Y,Z radius scaling
  26346. vertex_normal.x /= radiusX;
  26347. vertex_normal.y /= radiusY;
  26348. vertex_normal.z /= radiusZ;
  26349. vertex_normal.normalize();
  26350. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26351. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26352. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26353. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26354. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26355. uvs.push(uv_interp.x, uv_interp.y);
  26356. // push each vertex has member of a face
  26357. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26358. indices.push(current_indice);
  26359. current_indice++;
  26360. };
  26361. for (var i2 = 0; i2 < subdivisions; i2++) {
  26362. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26363. // face : (i1,i2) for /\ :
  26364. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26365. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26366. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26367. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26368. if (i1 + i2 + 1 < subdivisions) {
  26369. // face : (i1,i2)' for \/ :
  26370. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26371. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26372. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26373. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26374. }
  26375. }
  26376. }
  26377. }
  26378. // Sides
  26379. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26380. // Result
  26381. var vertexData = new VertexData();
  26382. vertexData.indices = indices;
  26383. vertexData.positions = positions;
  26384. vertexData.normals = normals;
  26385. vertexData.uvs = uvs;
  26386. return vertexData;
  26387. };
  26388. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26389. /**
  26390. * Creates the VertexData of the Polyhedron.
  26391. */
  26392. VertexData.CreatePolyhedron = function (options) {
  26393. // provided polyhedron types :
  26394. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26395. // 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)
  26396. var polyhedra = [];
  26397. 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]] };
  26398. 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]] };
  26399. polyhedra[2] = {
  26400. 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]],
  26401. 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]]
  26402. };
  26403. polyhedra[3] = {
  26404. 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]],
  26405. 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]]
  26406. };
  26407. polyhedra[4] = {
  26408. 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]],
  26409. 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]]
  26410. };
  26411. 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]] };
  26412. 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]] };
  26413. 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]] };
  26414. 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]] };
  26415. 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]] };
  26416. 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]] };
  26417. 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]] };
  26418. 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]] };
  26419. 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]] };
  26420. polyhedra[14] = {
  26421. 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]],
  26422. 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]]
  26423. };
  26424. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26425. var size = options.size;
  26426. var sizeX = options.sizeX || size || 1;
  26427. var sizeY = options.sizeY || size || 1;
  26428. var sizeZ = options.sizeZ || size || 1;
  26429. var data = options.custom || polyhedra[type];
  26430. var nbfaces = data.face.length;
  26431. var faceUV = options.faceUV || new Array(nbfaces);
  26432. var faceColors = options.faceColors;
  26433. var flat = (options.flat === undefined) ? true : options.flat;
  26434. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26435. var positions = [];
  26436. var indices = [];
  26437. var normals = [];
  26438. var uvs = [];
  26439. var colors = [];
  26440. var index = 0;
  26441. var faceIdx = 0; // face cursor in the array "indexes"
  26442. var indexes = [];
  26443. var i = 0;
  26444. var f = 0;
  26445. var u, v, ang, x, y, tmp;
  26446. // default face colors and UV if undefined
  26447. if (flat) {
  26448. for (f = 0; f < nbfaces; f++) {
  26449. if (faceColors && faceColors[f] === undefined) {
  26450. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26451. }
  26452. if (faceUV && faceUV[f] === undefined) {
  26453. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26454. }
  26455. }
  26456. }
  26457. if (!flat) {
  26458. for (i = 0; i < data.vertex.length; i++) {
  26459. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26460. uvs.push(0, 0);
  26461. }
  26462. for (f = 0; f < nbfaces; f++) {
  26463. for (i = 0; i < data.face[f].length - 2; i++) {
  26464. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26465. }
  26466. }
  26467. }
  26468. else {
  26469. for (f = 0; f < nbfaces; f++) {
  26470. var fl = data.face[f].length; // number of vertices of the current face
  26471. ang = 2 * Math.PI / fl;
  26472. x = 0.5 * Math.tan(ang / 2);
  26473. y = 0.5;
  26474. // positions, uvs, colors
  26475. for (i = 0; i < fl; i++) {
  26476. // positions
  26477. 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);
  26478. indexes.push(index);
  26479. index++;
  26480. // uvs
  26481. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26482. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26483. uvs.push(u, v);
  26484. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26485. y = x * Math.sin(ang) + y * Math.cos(ang);
  26486. x = tmp;
  26487. // colors
  26488. if (faceColors) {
  26489. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26490. }
  26491. }
  26492. // indices from indexes
  26493. for (i = 0; i < fl - 2; i++) {
  26494. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26495. }
  26496. faceIdx += fl;
  26497. }
  26498. }
  26499. VertexData.ComputeNormals(positions, indices, normals);
  26500. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26501. var vertexData = new VertexData();
  26502. vertexData.positions = positions;
  26503. vertexData.indices = indices;
  26504. vertexData.normals = normals;
  26505. vertexData.uvs = uvs;
  26506. if (faceColors && flat) {
  26507. vertexData.colors = colors;
  26508. }
  26509. return vertexData;
  26510. };
  26511. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26512. /**
  26513. * Creates the VertexData of the Torus Knot.
  26514. */
  26515. VertexData.CreateTorusKnot = function (options) {
  26516. var indices = [];
  26517. var positions = [];
  26518. var normals = [];
  26519. var uvs = [];
  26520. var radius = options.radius || 2;
  26521. var tube = options.tube || 0.5;
  26522. var radialSegments = options.radialSegments || 32;
  26523. var tubularSegments = options.tubularSegments || 32;
  26524. var p = options.p || 2;
  26525. var q = options.q || 3;
  26526. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26527. // Helper
  26528. var getPos = function (angle) {
  26529. var cu = Math.cos(angle);
  26530. var su = Math.sin(angle);
  26531. var quOverP = q / p * angle;
  26532. var cs = Math.cos(quOverP);
  26533. var tx = radius * (2 + cs) * 0.5 * cu;
  26534. var ty = radius * (2 + cs) * su * 0.5;
  26535. var tz = radius * Math.sin(quOverP) * 0.5;
  26536. return new BABYLON.Vector3(tx, ty, tz);
  26537. };
  26538. // Vertices
  26539. var i;
  26540. var j;
  26541. for (i = 0; i <= radialSegments; i++) {
  26542. var modI = i % radialSegments;
  26543. var u = modI / radialSegments * 2 * p * Math.PI;
  26544. var p1 = getPos(u);
  26545. var p2 = getPos(u + 0.01);
  26546. var tang = p2.subtract(p1);
  26547. var n = p2.add(p1);
  26548. var bitan = BABYLON.Vector3.Cross(tang, n);
  26549. n = BABYLON.Vector3.Cross(bitan, tang);
  26550. bitan.normalize();
  26551. n.normalize();
  26552. for (j = 0; j < tubularSegments; j++) {
  26553. var modJ = j % tubularSegments;
  26554. var v = modJ / tubularSegments * 2 * Math.PI;
  26555. var cx = -tube * Math.cos(v);
  26556. var cy = tube * Math.sin(v);
  26557. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26558. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26559. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26560. uvs.push(i / radialSegments);
  26561. uvs.push(j / tubularSegments);
  26562. }
  26563. }
  26564. for (i = 0; i < radialSegments; i++) {
  26565. for (j = 0; j < tubularSegments; j++) {
  26566. var jNext = (j + 1) % tubularSegments;
  26567. var a = i * tubularSegments + j;
  26568. var b = (i + 1) * tubularSegments + j;
  26569. var c = (i + 1) * tubularSegments + jNext;
  26570. var d = i * tubularSegments + jNext;
  26571. indices.push(d);
  26572. indices.push(b);
  26573. indices.push(a);
  26574. indices.push(d);
  26575. indices.push(c);
  26576. indices.push(b);
  26577. }
  26578. }
  26579. // Normals
  26580. VertexData.ComputeNormals(positions, indices, normals);
  26581. // Sides
  26582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26583. // Result
  26584. var vertexData = new VertexData();
  26585. vertexData.indices = indices;
  26586. vertexData.positions = positions;
  26587. vertexData.normals = normals;
  26588. vertexData.uvs = uvs;
  26589. return vertexData;
  26590. };
  26591. // Tools
  26592. /**
  26593. * @param {any} - positions (number[] or Float32Array)
  26594. * @param {any} - indices (number[] or Uint16Array)
  26595. * @param {any} - normals (number[] or Float32Array)
  26596. * options (optional) :
  26597. * facetPositions : optional array of facet positions (vector3)
  26598. * facetNormals : optional array of facet normals (vector3)
  26599. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26600. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26601. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26602. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26603. * bInfo : optional bounding info, required for facetPartitioning computation
  26604. */
  26605. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26606. // temporary scalar variables
  26607. var index = 0; // facet index
  26608. var p1p2x = 0.0; // p1p2 vector x coordinate
  26609. var p1p2y = 0.0; // p1p2 vector y coordinate
  26610. var p1p2z = 0.0; // p1p2 vector z coordinate
  26611. var p3p2x = 0.0; // p3p2 vector x coordinate
  26612. var p3p2y = 0.0; // p3p2 vector y coordinate
  26613. var p3p2z = 0.0; // p3p2 vector z coordinate
  26614. var faceNormalx = 0.0; // facet normal x coordinate
  26615. var faceNormaly = 0.0; // facet normal y coordinate
  26616. var faceNormalz = 0.0; // facet normal z coordinate
  26617. var length = 0.0; // facet normal length before normalization
  26618. var v1x = 0; // vector1 x index in the positions array
  26619. var v1y = 0; // vector1 y index in the positions array
  26620. var v1z = 0; // vector1 z index in the positions array
  26621. var v2x = 0; // vector2 x index in the positions array
  26622. var v2y = 0; // vector2 y index in the positions array
  26623. var v2z = 0; // vector2 z index in the positions array
  26624. var v3x = 0; // vector3 x index in the positions array
  26625. var v3y = 0; // vector3 y index in the positions array
  26626. var v3z = 0; // vector3 z index in the positions array
  26627. var computeFacetNormals = false;
  26628. var computeFacetPositions = false;
  26629. var computeFacetPartitioning = false;
  26630. var faceNormalSign = 1;
  26631. if (options) {
  26632. computeFacetNormals = (options.facetNormals) ? true : false;
  26633. computeFacetPositions = (options.facetPositions) ? true : false;
  26634. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26635. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26636. }
  26637. // facetPartitioning reinit if needed
  26638. if (computeFacetPartitioning) {
  26639. var ox = 0; // X partitioning index for facet position
  26640. var oy = 0; // Y partinioning index for facet position
  26641. var oz = 0; // Z partinioning index for facet position
  26642. var b1x = 0; // X partitioning index for facet v1 vertex
  26643. var b1y = 0; // Y partitioning index for facet v1 vertex
  26644. var b1z = 0; // z partitioning index for facet v1 vertex
  26645. var b2x = 0; // X partitioning index for facet v2 vertex
  26646. var b2y = 0; // Y partitioning index for facet v2 vertex
  26647. var b2z = 0; // Z partitioning index for facet v2 vertex
  26648. var b3x = 0; // X partitioning index for facet v3 vertex
  26649. var b3y = 0; // Y partitioning index for facet v3 vertex
  26650. var b3z = 0; // Z partitioning index for facet v3 vertex
  26651. var block_idx_o = 0; // facet barycenter block index
  26652. var block_idx_v1 = 0; // v1 vertex block index
  26653. var block_idx_v2 = 0; // v2 vertex block index
  26654. var block_idx_v3 = 0; // v3 vertex block index
  26655. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26656. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26657. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26658. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26659. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26660. var subSq = options.subDiv.max * options.subDiv.max;
  26661. options.facetPartitioning.length = 0;
  26662. }
  26663. // reset the normals
  26664. for (index = 0; index < positions.length; index++) {
  26665. normals[index] = 0.0;
  26666. }
  26667. // Loop : 1 indice triplet = 1 facet
  26668. var nbFaces = indices.length / 3;
  26669. for (index = 0; index < nbFaces; index++) {
  26670. // get the indexes of the coordinates of each vertex of the facet
  26671. v1x = indices[index * 3] * 3;
  26672. v1y = v1x + 1;
  26673. v1z = v1x + 2;
  26674. v2x = indices[index * 3 + 1] * 3;
  26675. v2y = v2x + 1;
  26676. v2z = v2x + 2;
  26677. v3x = indices[index * 3 + 2] * 3;
  26678. v3y = v3x + 1;
  26679. v3z = v3x + 2;
  26680. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26681. p1p2y = positions[v1y] - positions[v2y];
  26682. p1p2z = positions[v1z] - positions[v2z];
  26683. p3p2x = positions[v3x] - positions[v2x];
  26684. p3p2y = positions[v3y] - positions[v2y];
  26685. p3p2z = positions[v3z] - positions[v2z];
  26686. // compute the face normal with the cross product
  26687. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26688. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26689. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26690. // normalize this normal and store it in the array facetData
  26691. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26692. length = (length === 0) ? 1.0 : length;
  26693. faceNormalx /= length;
  26694. faceNormaly /= length;
  26695. faceNormalz /= length;
  26696. if (computeFacetNormals) {
  26697. options.facetNormals[index].x = faceNormalx;
  26698. options.facetNormals[index].y = faceNormaly;
  26699. options.facetNormals[index].z = faceNormalz;
  26700. }
  26701. if (computeFacetPositions) {
  26702. // compute and the facet barycenter coordinates in the array facetPositions
  26703. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26704. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26705. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26706. }
  26707. if (computeFacetPartitioning) {
  26708. // store the facet indexes in arrays in the main facetPartitioning array :
  26709. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26710. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26711. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26712. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26713. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26714. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26715. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26716. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26717. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26718. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26719. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26720. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26721. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26722. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26723. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26724. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26725. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26726. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26727. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26728. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26729. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26730. // push each facet index in each block containing the vertex
  26731. options.facetPartitioning[block_idx_v1].push(index);
  26732. if (block_idx_v2 != block_idx_v1) {
  26733. options.facetPartitioning[block_idx_v2].push(index);
  26734. }
  26735. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26736. options.facetPartitioning[block_idx_v3].push(index);
  26737. }
  26738. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26739. options.facetPartitioning[block_idx_o].push(index);
  26740. }
  26741. }
  26742. // compute the normals anyway
  26743. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26744. normals[v1y] += faceNormaly;
  26745. normals[v1z] += faceNormalz;
  26746. normals[v2x] += faceNormalx;
  26747. normals[v2y] += faceNormaly;
  26748. normals[v2z] += faceNormalz;
  26749. normals[v3x] += faceNormalx;
  26750. normals[v3y] += faceNormaly;
  26751. normals[v3z] += faceNormalz;
  26752. }
  26753. // last normalization of each normal
  26754. for (index = 0; index < normals.length / 3; index++) {
  26755. faceNormalx = normals[index * 3];
  26756. faceNormaly = normals[index * 3 + 1];
  26757. faceNormalz = normals[index * 3 + 2];
  26758. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26759. length = (length === 0) ? 1.0 : length;
  26760. faceNormalx /= length;
  26761. faceNormaly /= length;
  26762. faceNormalz /= length;
  26763. normals[index * 3] = faceNormalx;
  26764. normals[index * 3 + 1] = faceNormaly;
  26765. normals[index * 3 + 2] = faceNormalz;
  26766. }
  26767. };
  26768. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26769. var li = indices.length;
  26770. var ln = normals.length;
  26771. var i;
  26772. var n;
  26773. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26774. switch (sideOrientation) {
  26775. case BABYLON.Mesh.FRONTSIDE:
  26776. // nothing changed
  26777. break;
  26778. case BABYLON.Mesh.BACKSIDE:
  26779. var tmp;
  26780. // indices
  26781. for (i = 0; i < li; i += 3) {
  26782. tmp = indices[i];
  26783. indices[i] = indices[i + 2];
  26784. indices[i + 2] = tmp;
  26785. }
  26786. // normals
  26787. for (n = 0; n < ln; n++) {
  26788. normals[n] = -normals[n];
  26789. }
  26790. break;
  26791. case BABYLON.Mesh.DOUBLESIDE:
  26792. // positions
  26793. var lp = positions.length;
  26794. var l = lp / 3;
  26795. for (var p = 0; p < lp; p++) {
  26796. positions[lp + p] = positions[p];
  26797. }
  26798. // indices
  26799. for (i = 0; i < li; i += 3) {
  26800. indices[i + li] = indices[i + 2] + l;
  26801. indices[i + 1 + li] = indices[i + 1] + l;
  26802. indices[i + 2 + li] = indices[i] + l;
  26803. }
  26804. // normals
  26805. for (n = 0; n < ln; n++) {
  26806. normals[ln + n] = -normals[n];
  26807. }
  26808. // uvs
  26809. var lu = uvs.length;
  26810. var u = 0;
  26811. for (u = 0; u < lu; u++) {
  26812. uvs[u + lu] = uvs[u];
  26813. }
  26814. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26815. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26816. u = 0;
  26817. for (i = 0; i < lu / 2; i++) {
  26818. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26819. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26820. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26821. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26822. u += 2;
  26823. }
  26824. break;
  26825. }
  26826. };
  26827. /**
  26828. * Creates a new VertexData from the imported parameters.
  26829. */
  26830. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26831. var vertexData = new VertexData();
  26832. // positions
  26833. var positions = parsedVertexData.positions;
  26834. if (positions) {
  26835. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26836. }
  26837. // normals
  26838. var normals = parsedVertexData.normals;
  26839. if (normals) {
  26840. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26841. }
  26842. // tangents
  26843. var tangents = parsedVertexData.tangents;
  26844. if (tangents) {
  26845. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26846. }
  26847. // uvs
  26848. var uvs = parsedVertexData.uvs;
  26849. if (uvs) {
  26850. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26851. }
  26852. // uv2s
  26853. var uv2s = parsedVertexData.uv2s;
  26854. if (uv2s) {
  26855. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26856. }
  26857. // uv3s
  26858. var uv3s = parsedVertexData.uv3s;
  26859. if (uv3s) {
  26860. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26861. }
  26862. // uv4s
  26863. var uv4s = parsedVertexData.uv4s;
  26864. if (uv4s) {
  26865. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26866. }
  26867. // uv5s
  26868. var uv5s = parsedVertexData.uv5s;
  26869. if (uv5s) {
  26870. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26871. }
  26872. // uv6s
  26873. var uv6s = parsedVertexData.uv6s;
  26874. if (uv6s) {
  26875. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26876. }
  26877. // colors
  26878. var colors = parsedVertexData.colors;
  26879. if (colors) {
  26880. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26881. }
  26882. // matricesIndices
  26883. var matricesIndices = parsedVertexData.matricesIndices;
  26884. if (matricesIndices) {
  26885. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26886. }
  26887. // matricesWeights
  26888. var matricesWeights = parsedVertexData.matricesWeights;
  26889. if (matricesWeights) {
  26890. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26891. }
  26892. // indices
  26893. var indices = parsedVertexData.indices;
  26894. if (indices) {
  26895. vertexData.indices = indices;
  26896. }
  26897. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26898. };
  26899. return VertexData;
  26900. }());
  26901. BABYLON.VertexData = VertexData;
  26902. })(BABYLON || (BABYLON = {}));
  26903. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26904. var BABYLON;
  26905. (function (BABYLON) {
  26906. var Geometry = (function () {
  26907. function Geometry(id, scene, vertexData, updatable, mesh) {
  26908. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26909. this._totalVertices = 0;
  26910. this._isDisposed = false;
  26911. this.id = id;
  26912. this._engine = scene.getEngine();
  26913. this._meshes = [];
  26914. this._scene = scene;
  26915. //Init vertex buffer cache
  26916. this._vertexBuffers = {};
  26917. this._indices = [];
  26918. // vertexData
  26919. if (vertexData) {
  26920. this.setAllVerticesData(vertexData, updatable);
  26921. }
  26922. else {
  26923. this._totalVertices = 0;
  26924. this._indices = [];
  26925. }
  26926. if (this._engine.getCaps().vertexArrayObject) {
  26927. this._vertexArrayObjects = {};
  26928. }
  26929. // applyToMesh
  26930. if (mesh) {
  26931. if (mesh.getClassName() === "LinesMesh") {
  26932. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26933. this.updateExtend();
  26934. }
  26935. this.applyToMesh(mesh);
  26936. mesh.computeWorldMatrix(true);
  26937. }
  26938. }
  26939. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26940. /**
  26941. * 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
  26942. * @returns The Bias Vector
  26943. */
  26944. get: function () {
  26945. return this._boundingBias;
  26946. },
  26947. set: function (value) {
  26948. if (this._boundingBias && this._boundingBias.equals(value)) {
  26949. return;
  26950. }
  26951. this._boundingBias = value.clone();
  26952. this.updateBoundingInfo(true, null);
  26953. },
  26954. enumerable: true,
  26955. configurable: true
  26956. });
  26957. Object.defineProperty(Geometry.prototype, "extend", {
  26958. get: function () {
  26959. return this._extend;
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Geometry.prototype.getScene = function () {
  26965. return this._scene;
  26966. };
  26967. Geometry.prototype.getEngine = function () {
  26968. return this._engine;
  26969. };
  26970. Geometry.prototype.isReady = function () {
  26971. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26972. };
  26973. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26974. get: function () {
  26975. for (var index = 0; index < this._meshes.length; index++) {
  26976. if (!this._meshes[index].doNotSerialize) {
  26977. return false;
  26978. }
  26979. }
  26980. return true;
  26981. },
  26982. enumerable: true,
  26983. configurable: true
  26984. });
  26985. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26986. vertexData.applyToGeometry(this, updatable);
  26987. this.notifyUpdate();
  26988. };
  26989. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26990. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26991. this.setVerticesBuffer(buffer);
  26992. };
  26993. Geometry.prototype.removeVerticesData = function (kind) {
  26994. if (this._vertexBuffers[kind]) {
  26995. this._vertexBuffers[kind].dispose();
  26996. delete this._vertexBuffers[kind];
  26997. }
  26998. };
  26999. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27000. var kind = buffer.getKind();
  27001. if (this._vertexBuffers[kind]) {
  27002. this._vertexBuffers[kind].dispose();
  27003. }
  27004. this._vertexBuffers[kind] = buffer;
  27005. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27006. var data = buffer.getData();
  27007. var stride = buffer.getStrideSize();
  27008. this._totalVertices = data.length / stride;
  27009. this.updateExtend(data, stride);
  27010. this._resetPointsArrayCache();
  27011. var meshes = this._meshes;
  27012. var numOfMeshes = meshes.length;
  27013. for (var index = 0; index < numOfMeshes; index++) {
  27014. var mesh = meshes[index];
  27015. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27016. mesh._createGlobalSubMesh();
  27017. mesh.computeWorldMatrix(true);
  27018. }
  27019. }
  27020. this.notifyUpdate(kind);
  27021. if (this._vertexArrayObjects) {
  27022. this._disposeVertexArrayObjects();
  27023. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27024. }
  27025. };
  27026. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27027. var vertexBuffer = this.getVertexBuffer(kind);
  27028. if (!vertexBuffer) {
  27029. return;
  27030. }
  27031. vertexBuffer.updateDirectly(data, offset);
  27032. this.notifyUpdate(kind);
  27033. };
  27034. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27035. var vertexBuffer = this.getVertexBuffer(kind);
  27036. if (!vertexBuffer) {
  27037. return;
  27038. }
  27039. vertexBuffer.update(data);
  27040. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27041. var stride = vertexBuffer.getStrideSize();
  27042. this._totalVertices = data.length / stride;
  27043. this.updateBoundingInfo(updateExtends, data);
  27044. }
  27045. this.notifyUpdate(kind);
  27046. };
  27047. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27048. if (updateExtends) {
  27049. this.updateExtend(data);
  27050. }
  27051. var meshes = this._meshes;
  27052. var numOfMeshes = meshes.length;
  27053. this._resetPointsArrayCache();
  27054. for (var index = 0; index < numOfMeshes; index++) {
  27055. var mesh = meshes[index];
  27056. if (updateExtends) {
  27057. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27058. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27059. var subMesh = mesh.subMeshes[subIndex];
  27060. subMesh.refreshBoundingInfo();
  27061. }
  27062. }
  27063. }
  27064. };
  27065. Geometry.prototype._bind = function (effect, indexToBind) {
  27066. if (indexToBind === void 0) { indexToBind = undefined; }
  27067. if (indexToBind === undefined) {
  27068. indexToBind = this._indexBuffer;
  27069. }
  27070. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27071. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27072. return;
  27073. }
  27074. // Using VAO
  27075. if (!this._vertexArrayObjects[effect.key]) {
  27076. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27077. }
  27078. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27079. };
  27080. Geometry.prototype.getTotalVertices = function () {
  27081. if (!this.isReady()) {
  27082. return 0;
  27083. }
  27084. return this._totalVertices;
  27085. };
  27086. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27087. var vertexBuffer = this.getVertexBuffer(kind);
  27088. if (!vertexBuffer) {
  27089. return null;
  27090. }
  27091. var orig = vertexBuffer.getData();
  27092. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27093. return orig;
  27094. }
  27095. else {
  27096. var len = orig.length;
  27097. var copy = [];
  27098. for (var i = 0; i < len; i++) {
  27099. copy.push(orig[i]);
  27100. }
  27101. return copy;
  27102. }
  27103. };
  27104. Geometry.prototype.getVertexBuffer = function (kind) {
  27105. if (!this.isReady()) {
  27106. return null;
  27107. }
  27108. return this._vertexBuffers[kind];
  27109. };
  27110. Geometry.prototype.getVertexBuffers = function () {
  27111. if (!this.isReady()) {
  27112. return null;
  27113. }
  27114. return this._vertexBuffers;
  27115. };
  27116. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27117. if (!this._vertexBuffers) {
  27118. if (this._delayInfo) {
  27119. return this._delayInfo.indexOf(kind) !== -1;
  27120. }
  27121. return false;
  27122. }
  27123. return this._vertexBuffers[kind] !== undefined;
  27124. };
  27125. Geometry.prototype.getVerticesDataKinds = function () {
  27126. var result = [];
  27127. var kind;
  27128. if (!this._vertexBuffers && this._delayInfo) {
  27129. for (kind in this._delayInfo) {
  27130. result.push(kind);
  27131. }
  27132. }
  27133. else {
  27134. for (kind in this._vertexBuffers) {
  27135. result.push(kind);
  27136. }
  27137. }
  27138. return result;
  27139. };
  27140. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27141. if (this._indexBuffer) {
  27142. this._engine._releaseBuffer(this._indexBuffer);
  27143. }
  27144. this._disposeVertexArrayObjects();
  27145. this._indices = indices;
  27146. if (this._meshes.length !== 0 && this._indices) {
  27147. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27148. }
  27149. if (totalVertices !== undefined) {
  27150. this._totalVertices = totalVertices;
  27151. }
  27152. var meshes = this._meshes;
  27153. var numOfMeshes = meshes.length;
  27154. for (var index = 0; index < numOfMeshes; index++) {
  27155. meshes[index]._createGlobalSubMesh();
  27156. }
  27157. this.notifyUpdate();
  27158. };
  27159. Geometry.prototype.getTotalIndices = function () {
  27160. if (!this.isReady()) {
  27161. return 0;
  27162. }
  27163. return this._indices.length;
  27164. };
  27165. Geometry.prototype.getIndices = function (copyWhenShared) {
  27166. if (!this.isReady()) {
  27167. return null;
  27168. }
  27169. var orig = this._indices;
  27170. if (!copyWhenShared || this._meshes.length === 1) {
  27171. return orig;
  27172. }
  27173. else {
  27174. var len = orig.length;
  27175. var copy = [];
  27176. for (var i = 0; i < len; i++) {
  27177. copy.push(orig[i]);
  27178. }
  27179. return copy;
  27180. }
  27181. };
  27182. Geometry.prototype.getIndexBuffer = function () {
  27183. if (!this.isReady()) {
  27184. return null;
  27185. }
  27186. return this._indexBuffer;
  27187. };
  27188. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27189. if (!effect || !this._vertexArrayObjects) {
  27190. return;
  27191. }
  27192. if (this._vertexArrayObjects[effect.key]) {
  27193. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27194. delete this._vertexArrayObjects[effect.key];
  27195. }
  27196. };
  27197. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27198. var meshes = this._meshes;
  27199. var index = meshes.indexOf(mesh);
  27200. if (index === -1) {
  27201. return;
  27202. }
  27203. meshes.splice(index, 1);
  27204. mesh._geometry = null;
  27205. if (meshes.length === 0 && shouldDispose) {
  27206. this.dispose();
  27207. }
  27208. };
  27209. Geometry.prototype.applyToMesh = function (mesh) {
  27210. if (mesh._geometry === this) {
  27211. return;
  27212. }
  27213. var previousGeometry = mesh._geometry;
  27214. if (previousGeometry) {
  27215. previousGeometry.releaseForMesh(mesh);
  27216. }
  27217. var meshes = this._meshes;
  27218. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27219. mesh._geometry = this;
  27220. this._scene.pushGeometry(this);
  27221. meshes.push(mesh);
  27222. if (this.isReady()) {
  27223. this._applyToMesh(mesh);
  27224. }
  27225. else {
  27226. mesh._boundingInfo = this._boundingInfo;
  27227. }
  27228. };
  27229. Geometry.prototype.updateExtend = function (data, stride) {
  27230. if (data === void 0) { data = null; }
  27231. if (!data) {
  27232. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27233. }
  27234. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27235. };
  27236. Geometry.prototype._applyToMesh = function (mesh) {
  27237. var numOfMeshes = this._meshes.length;
  27238. // vertexBuffers
  27239. for (var kind in this._vertexBuffers) {
  27240. if (numOfMeshes === 1) {
  27241. this._vertexBuffers[kind].create();
  27242. }
  27243. var buffer = this._vertexBuffers[kind].getBuffer();
  27244. if (buffer)
  27245. buffer.references = numOfMeshes;
  27246. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27247. if (!this._extend) {
  27248. this.updateExtend(this._vertexBuffers[kind].getData());
  27249. }
  27250. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27251. mesh._createGlobalSubMesh();
  27252. //bounding info was just created again, world matrix should be applied again.
  27253. mesh._updateBoundingInfo();
  27254. }
  27255. }
  27256. // indexBuffer
  27257. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27258. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27259. }
  27260. if (this._indexBuffer) {
  27261. this._indexBuffer.references = numOfMeshes;
  27262. }
  27263. };
  27264. Geometry.prototype.notifyUpdate = function (kind) {
  27265. if (this.onGeometryUpdated) {
  27266. this.onGeometryUpdated(this, kind);
  27267. }
  27268. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27269. var mesh = _a[_i];
  27270. mesh._markSubMeshesAsAttributesDirty();
  27271. }
  27272. };
  27273. Geometry.prototype.load = function (scene, onLoaded) {
  27274. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27275. return;
  27276. }
  27277. if (this.isReady()) {
  27278. if (onLoaded) {
  27279. onLoaded();
  27280. }
  27281. return;
  27282. }
  27283. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27284. this._queueLoad(scene, onLoaded);
  27285. };
  27286. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27287. var _this = this;
  27288. scene._addPendingData(this);
  27289. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27290. _this._delayLoadingFunction(JSON.parse(data), _this);
  27291. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27292. _this._delayInfo = [];
  27293. scene._removePendingData(_this);
  27294. var meshes = _this._meshes;
  27295. var numOfMeshes = meshes.length;
  27296. for (var index = 0; index < numOfMeshes; index++) {
  27297. _this._applyToMesh(meshes[index]);
  27298. }
  27299. if (onLoaded) {
  27300. onLoaded();
  27301. }
  27302. }, function () { }, scene.database);
  27303. };
  27304. /**
  27305. * Invert the geometry to move from a right handed system to a left handed one.
  27306. */
  27307. Geometry.prototype.toLeftHanded = function () {
  27308. // Flip faces
  27309. var tIndices = this.getIndices(false);
  27310. if (tIndices != null && tIndices.length > 0) {
  27311. for (var i = 0; i < tIndices.length; i += 3) {
  27312. var tTemp = tIndices[i + 0];
  27313. tIndices[i + 0] = tIndices[i + 2];
  27314. tIndices[i + 2] = tTemp;
  27315. }
  27316. this.setIndices(tIndices);
  27317. }
  27318. // Negate position.z
  27319. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27320. if (tPositions != null && tPositions.length > 0) {
  27321. for (var i = 0; i < tPositions.length; i += 3) {
  27322. tPositions[i + 2] = -tPositions[i + 2];
  27323. }
  27324. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27325. }
  27326. // Negate normal.z
  27327. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27328. if (tNormals != null && tNormals.length > 0) {
  27329. for (var i = 0; i < tNormals.length; i += 3) {
  27330. tNormals[i + 2] = -tNormals[i + 2];
  27331. }
  27332. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27333. }
  27334. };
  27335. // Cache
  27336. Geometry.prototype._resetPointsArrayCache = function () {
  27337. this._positions = null;
  27338. };
  27339. Geometry.prototype._generatePointsArray = function () {
  27340. if (this._positions)
  27341. return true;
  27342. this._positions = [];
  27343. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27344. if (!data) {
  27345. return false;
  27346. }
  27347. for (var index = 0; index < data.length; index += 3) {
  27348. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27349. }
  27350. return true;
  27351. };
  27352. Geometry.prototype.isDisposed = function () {
  27353. return this._isDisposed;
  27354. };
  27355. Geometry.prototype._disposeVertexArrayObjects = function () {
  27356. if (this._vertexArrayObjects) {
  27357. for (var kind in this._vertexArrayObjects) {
  27358. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27359. }
  27360. this._vertexArrayObjects = {};
  27361. }
  27362. };
  27363. Geometry.prototype.dispose = function () {
  27364. var meshes = this._meshes;
  27365. var numOfMeshes = meshes.length;
  27366. var index;
  27367. for (index = 0; index < numOfMeshes; index++) {
  27368. this.releaseForMesh(meshes[index]);
  27369. }
  27370. this._meshes = [];
  27371. this._disposeVertexArrayObjects();
  27372. for (var kind in this._vertexBuffers) {
  27373. this._vertexBuffers[kind].dispose();
  27374. }
  27375. this._vertexBuffers = {};
  27376. this._totalVertices = 0;
  27377. if (this._indexBuffer) {
  27378. this._engine._releaseBuffer(this._indexBuffer);
  27379. }
  27380. this._indexBuffer = null;
  27381. this._indices = [];
  27382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27383. this.delayLoadingFile = null;
  27384. this._delayLoadingFunction = null;
  27385. this._delayInfo = [];
  27386. this._boundingInfo = null;
  27387. this._scene.removeGeometry(this);
  27388. this._isDisposed = true;
  27389. };
  27390. Geometry.prototype.copy = function (id) {
  27391. var vertexData = new BABYLON.VertexData();
  27392. vertexData.indices = [];
  27393. var indices = this.getIndices();
  27394. for (var index = 0; index < indices.length; index++) {
  27395. vertexData.indices.push(indices[index]);
  27396. }
  27397. var updatable = false;
  27398. var stopChecking = false;
  27399. var kind;
  27400. for (kind in this._vertexBuffers) {
  27401. // using slice() to make a copy of the array and not just reference it
  27402. var data = this.getVerticesData(kind);
  27403. if (data instanceof Float32Array) {
  27404. vertexData.set(new Float32Array(data), kind);
  27405. }
  27406. else {
  27407. vertexData.set(data.slice(0), kind);
  27408. }
  27409. if (!stopChecking) {
  27410. updatable = this.getVertexBuffer(kind).isUpdatable();
  27411. stopChecking = !updatable;
  27412. }
  27413. }
  27414. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27415. geometry.delayLoadState = this.delayLoadState;
  27416. geometry.delayLoadingFile = this.delayLoadingFile;
  27417. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27418. for (kind in this._delayInfo) {
  27419. geometry._delayInfo = geometry._delayInfo || [];
  27420. geometry._delayInfo.push(kind);
  27421. }
  27422. // Bounding info
  27423. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27424. return geometry;
  27425. };
  27426. Geometry.prototype.serialize = function () {
  27427. var serializationObject = {};
  27428. serializationObject.id = this.id;
  27429. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27430. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27431. }
  27432. return serializationObject;
  27433. };
  27434. Geometry.prototype.toNumberArray = function (origin) {
  27435. if (Array.isArray(origin)) {
  27436. return origin;
  27437. }
  27438. else {
  27439. return Array.prototype.slice.call(origin);
  27440. }
  27441. };
  27442. Geometry.prototype.serializeVerticeData = function () {
  27443. var serializationObject = this.serialize();
  27444. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27445. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27446. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27447. serializationObject.positions._updatable = true;
  27448. }
  27449. }
  27450. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27451. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27452. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27453. serializationObject.normals._updatable = true;
  27454. }
  27455. }
  27456. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27457. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27458. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27459. serializationObject.uvs._updatable = true;
  27460. }
  27461. }
  27462. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27463. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27464. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27465. serializationObject.uv2s._updatable = true;
  27466. }
  27467. }
  27468. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27469. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27470. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27471. serializationObject.uv3s._updatable = true;
  27472. }
  27473. }
  27474. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27475. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27476. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27477. serializationObject.uv4s._updatable = true;
  27478. }
  27479. }
  27480. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27481. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27482. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27483. serializationObject.uv5s._updatable = true;
  27484. }
  27485. }
  27486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27487. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27488. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27489. serializationObject.uv6s._updatable = true;
  27490. }
  27491. }
  27492. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27493. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27494. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27495. serializationObject.colors._updatable = true;
  27496. }
  27497. }
  27498. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27499. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27500. serializationObject.matricesIndices._isExpanded = true;
  27501. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27502. serializationObject.matricesIndices._updatable = true;
  27503. }
  27504. }
  27505. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27506. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27507. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27508. serializationObject.matricesWeights._updatable = true;
  27509. }
  27510. }
  27511. serializationObject.indices = this.toNumberArray(this.getIndices());
  27512. return serializationObject;
  27513. };
  27514. // Statics
  27515. Geometry.ExtractFromMesh = function (mesh, id) {
  27516. var geometry = mesh._geometry;
  27517. if (!geometry) {
  27518. return null;
  27519. }
  27520. return geometry.copy(id);
  27521. };
  27522. /**
  27523. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27524. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27525. * Be aware Math.random() could cause collisions, but:
  27526. * "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"
  27527. */
  27528. Geometry.RandomId = function () {
  27529. return BABYLON.Tools.RandomId();
  27530. };
  27531. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27532. var scene = mesh.getScene();
  27533. // Geometry
  27534. var geometryId = parsedGeometry.geometryId;
  27535. if (geometryId) {
  27536. var geometry = scene.getGeometryByID(geometryId);
  27537. if (geometry) {
  27538. geometry.applyToMesh(mesh);
  27539. }
  27540. }
  27541. else if (parsedGeometry instanceof ArrayBuffer) {
  27542. var binaryInfo = mesh._binaryInfo;
  27543. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27544. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27545. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27546. }
  27547. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27548. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27549. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27550. }
  27551. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27552. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27553. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27554. }
  27555. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27556. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27557. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27558. }
  27559. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27560. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27561. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27562. }
  27563. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27564. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27565. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27566. }
  27567. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27568. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27569. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27570. }
  27571. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27572. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27573. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27574. }
  27575. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27576. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27577. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27578. }
  27579. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27580. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27581. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27582. }
  27583. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27584. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27585. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27586. }
  27587. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27588. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27589. mesh.setIndices(indicesData);
  27590. }
  27591. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27592. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27593. mesh.subMeshes = [];
  27594. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27595. var materialIndex = subMeshesData[(i * 5) + 0];
  27596. var verticesStart = subMeshesData[(i * 5) + 1];
  27597. var verticesCount = subMeshesData[(i * 5) + 2];
  27598. var indexStart = subMeshesData[(i * 5) + 3];
  27599. var indexCount = subMeshesData[(i * 5) + 4];
  27600. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27601. }
  27602. }
  27603. }
  27604. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27605. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27606. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27607. if (parsedGeometry.uvs) {
  27608. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27609. }
  27610. if (parsedGeometry.uvs2) {
  27611. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27612. }
  27613. if (parsedGeometry.uvs3) {
  27614. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27615. }
  27616. if (parsedGeometry.uvs4) {
  27617. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27618. }
  27619. if (parsedGeometry.uvs5) {
  27620. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27621. }
  27622. if (parsedGeometry.uvs6) {
  27623. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27624. }
  27625. if (parsedGeometry.colors) {
  27626. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27627. }
  27628. if (parsedGeometry.matricesIndices) {
  27629. if (!parsedGeometry.matricesIndices._isExpanded) {
  27630. var floatIndices = [];
  27631. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27632. var matricesIndex = parsedGeometry.matricesIndices[i];
  27633. floatIndices.push(matricesIndex & 0x000000FF);
  27634. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27635. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27636. floatIndices.push(matricesIndex >> 24);
  27637. }
  27638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27639. }
  27640. else {
  27641. delete parsedGeometry.matricesIndices._isExpanded;
  27642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27643. }
  27644. }
  27645. if (parsedGeometry.matricesIndicesExtra) {
  27646. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27647. var floatIndices = [];
  27648. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27649. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27650. floatIndices.push(matricesIndex & 0x000000FF);
  27651. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27652. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27653. floatIndices.push(matricesIndex >> 24);
  27654. }
  27655. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27656. }
  27657. else {
  27658. delete parsedGeometry.matricesIndices._isExpanded;
  27659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27660. }
  27661. }
  27662. if (parsedGeometry.matricesWeights) {
  27663. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27664. }
  27665. if (parsedGeometry.matricesWeightsExtra) {
  27666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27667. }
  27668. mesh.setIndices(parsedGeometry.indices);
  27669. }
  27670. // SubMeshes
  27671. if (parsedGeometry.subMeshes) {
  27672. mesh.subMeshes = [];
  27673. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27674. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27675. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27676. }
  27677. }
  27678. // Flat shading
  27679. if (mesh._shouldGenerateFlatShading) {
  27680. mesh.convertToFlatShadedMesh();
  27681. delete mesh._shouldGenerateFlatShading;
  27682. }
  27683. // Update
  27684. mesh.computeWorldMatrix(true);
  27685. // Octree
  27686. if (scene['_selectionOctree']) {
  27687. scene['_selectionOctree'].addMesh(mesh);
  27688. }
  27689. };
  27690. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27691. if (scene.getGeometryByID(parsedVertexData.id)) {
  27692. return null; // null since geometry could be something else than a box...
  27693. }
  27694. var geometry = new Geometry(parsedVertexData.id, scene);
  27695. if (BABYLON.Tags) {
  27696. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27697. }
  27698. if (parsedVertexData.delayLoadingFile) {
  27699. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27700. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27701. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27702. geometry._delayInfo = [];
  27703. if (parsedVertexData.hasUVs) {
  27704. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27705. }
  27706. if (parsedVertexData.hasUVs2) {
  27707. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27708. }
  27709. if (parsedVertexData.hasUVs3) {
  27710. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27711. }
  27712. if (parsedVertexData.hasUVs4) {
  27713. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27714. }
  27715. if (parsedVertexData.hasUVs5) {
  27716. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27717. }
  27718. if (parsedVertexData.hasUVs6) {
  27719. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27720. }
  27721. if (parsedVertexData.hasColors) {
  27722. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27723. }
  27724. if (parsedVertexData.hasMatricesIndices) {
  27725. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27726. }
  27727. if (parsedVertexData.hasMatricesWeights) {
  27728. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27729. }
  27730. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27731. }
  27732. else {
  27733. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27734. }
  27735. scene.pushGeometry(geometry, true);
  27736. return geometry;
  27737. };
  27738. return Geometry;
  27739. }());
  27740. BABYLON.Geometry = Geometry;
  27741. /////// Primitives //////////////////////////////////////////////
  27742. (function (Geometry) {
  27743. var Primitives;
  27744. (function (Primitives) {
  27745. /// Abstract class
  27746. var _Primitive = (function (_super) {
  27747. __extends(_Primitive, _super);
  27748. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27749. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27750. _this._canBeRegenerated = _canBeRegenerated;
  27751. _this._beingRegenerated = true;
  27752. _this.regenerate();
  27753. _this._beingRegenerated = false;
  27754. return _this;
  27755. }
  27756. _Primitive.prototype.canBeRegenerated = function () {
  27757. return this._canBeRegenerated;
  27758. };
  27759. _Primitive.prototype.regenerate = function () {
  27760. if (!this._canBeRegenerated) {
  27761. return;
  27762. }
  27763. this._beingRegenerated = true;
  27764. this.setAllVerticesData(this._regenerateVertexData(), false);
  27765. this._beingRegenerated = false;
  27766. };
  27767. _Primitive.prototype.asNewGeometry = function (id) {
  27768. return _super.prototype.copy.call(this, id);
  27769. };
  27770. // overrides
  27771. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27772. if (!this._beingRegenerated) {
  27773. return;
  27774. }
  27775. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27776. };
  27777. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27778. if (!this._beingRegenerated) {
  27779. return;
  27780. }
  27781. _super.prototype.setVerticesData.call(this, kind, data, false);
  27782. };
  27783. // to override
  27784. // protected
  27785. _Primitive.prototype._regenerateVertexData = function () {
  27786. throw new Error("Abstract method");
  27787. };
  27788. _Primitive.prototype.copy = function (id) {
  27789. throw new Error("Must be overriden in sub-classes.");
  27790. };
  27791. _Primitive.prototype.serialize = function () {
  27792. var serializationObject = _super.prototype.serialize.call(this);
  27793. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27794. return serializationObject;
  27795. };
  27796. return _Primitive;
  27797. }(Geometry));
  27798. Primitives._Primitive = _Primitive;
  27799. var Ribbon = (function (_super) {
  27800. __extends(Ribbon, _super);
  27801. // Members
  27802. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27803. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27804. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27805. _this.pathArray = pathArray;
  27806. _this.closeArray = closeArray;
  27807. _this.closePath = closePath;
  27808. _this.offset = offset;
  27809. _this.side = side;
  27810. return _this;
  27811. }
  27812. Ribbon.prototype._regenerateVertexData = function () {
  27813. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27814. };
  27815. Ribbon.prototype.copy = function (id) {
  27816. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27817. };
  27818. return Ribbon;
  27819. }(_Primitive));
  27820. Primitives.Ribbon = Ribbon;
  27821. var Box = (function (_super) {
  27822. __extends(Box, _super);
  27823. // Members
  27824. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27825. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27826. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27827. _this.size = size;
  27828. _this.side = side;
  27829. return _this;
  27830. }
  27831. Box.prototype._regenerateVertexData = function () {
  27832. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27833. };
  27834. Box.prototype.copy = function (id) {
  27835. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27836. };
  27837. Box.prototype.serialize = function () {
  27838. var serializationObject = _super.prototype.serialize.call(this);
  27839. serializationObject.size = this.size;
  27840. return serializationObject;
  27841. };
  27842. Box.Parse = function (parsedBox, scene) {
  27843. if (scene.getGeometryByID(parsedBox.id)) {
  27844. return null; // null since geometry could be something else than a box...
  27845. }
  27846. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27847. if (BABYLON.Tags) {
  27848. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27849. }
  27850. scene.pushGeometry(box, true);
  27851. return box;
  27852. };
  27853. return Box;
  27854. }(_Primitive));
  27855. Primitives.Box = Box;
  27856. var Sphere = (function (_super) {
  27857. __extends(Sphere, _super);
  27858. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27859. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27860. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27861. _this.segments = segments;
  27862. _this.diameter = diameter;
  27863. _this.side = side;
  27864. return _this;
  27865. }
  27866. Sphere.prototype._regenerateVertexData = function () {
  27867. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27868. };
  27869. Sphere.prototype.copy = function (id) {
  27870. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27871. };
  27872. Sphere.prototype.serialize = function () {
  27873. var serializationObject = _super.prototype.serialize.call(this);
  27874. serializationObject.segments = this.segments;
  27875. serializationObject.diameter = this.diameter;
  27876. return serializationObject;
  27877. };
  27878. Sphere.Parse = function (parsedSphere, scene) {
  27879. if (scene.getGeometryByID(parsedSphere.id)) {
  27880. return null; // null since geometry could be something else than a sphere...
  27881. }
  27882. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27883. if (BABYLON.Tags) {
  27884. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27885. }
  27886. scene.pushGeometry(sphere, true);
  27887. return sphere;
  27888. };
  27889. return Sphere;
  27890. }(_Primitive));
  27891. Primitives.Sphere = Sphere;
  27892. var Disc = (function (_super) {
  27893. __extends(Disc, _super);
  27894. // Members
  27895. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27896. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27897. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27898. _this.radius = radius;
  27899. _this.tessellation = tessellation;
  27900. _this.side = side;
  27901. return _this;
  27902. }
  27903. Disc.prototype._regenerateVertexData = function () {
  27904. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27905. };
  27906. Disc.prototype.copy = function (id) {
  27907. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27908. };
  27909. return Disc;
  27910. }(_Primitive));
  27911. Primitives.Disc = Disc;
  27912. var Cylinder = (function (_super) {
  27913. __extends(Cylinder, _super);
  27914. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27915. if (subdivisions === void 0) { subdivisions = 1; }
  27916. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27917. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27918. _this.height = height;
  27919. _this.diameterTop = diameterTop;
  27920. _this.diameterBottom = diameterBottom;
  27921. _this.tessellation = tessellation;
  27922. _this.subdivisions = subdivisions;
  27923. _this.side = side;
  27924. return _this;
  27925. }
  27926. Cylinder.prototype._regenerateVertexData = function () {
  27927. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27928. };
  27929. Cylinder.prototype.copy = function (id) {
  27930. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27931. };
  27932. Cylinder.prototype.serialize = function () {
  27933. var serializationObject = _super.prototype.serialize.call(this);
  27934. serializationObject.height = this.height;
  27935. serializationObject.diameterTop = this.diameterTop;
  27936. serializationObject.diameterBottom = this.diameterBottom;
  27937. serializationObject.tessellation = this.tessellation;
  27938. return serializationObject;
  27939. };
  27940. Cylinder.Parse = function (parsedCylinder, scene) {
  27941. if (scene.getGeometryByID(parsedCylinder.id)) {
  27942. return null; // null since geometry could be something else than a cylinder...
  27943. }
  27944. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27945. if (BABYLON.Tags) {
  27946. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27947. }
  27948. scene.pushGeometry(cylinder, true);
  27949. return cylinder;
  27950. };
  27951. return Cylinder;
  27952. }(_Primitive));
  27953. Primitives.Cylinder = Cylinder;
  27954. var Torus = (function (_super) {
  27955. __extends(Torus, _super);
  27956. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27957. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27958. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27959. _this.diameter = diameter;
  27960. _this.thickness = thickness;
  27961. _this.tessellation = tessellation;
  27962. _this.side = side;
  27963. return _this;
  27964. }
  27965. Torus.prototype._regenerateVertexData = function () {
  27966. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27967. };
  27968. Torus.prototype.copy = function (id) {
  27969. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27970. };
  27971. Torus.prototype.serialize = function () {
  27972. var serializationObject = _super.prototype.serialize.call(this);
  27973. serializationObject.diameter = this.diameter;
  27974. serializationObject.thickness = this.thickness;
  27975. serializationObject.tessellation = this.tessellation;
  27976. return serializationObject;
  27977. };
  27978. Torus.Parse = function (parsedTorus, scene) {
  27979. if (scene.getGeometryByID(parsedTorus.id)) {
  27980. return null; // null since geometry could be something else than a torus...
  27981. }
  27982. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27983. if (BABYLON.Tags) {
  27984. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27985. }
  27986. scene.pushGeometry(torus, true);
  27987. return torus;
  27988. };
  27989. return Torus;
  27990. }(_Primitive));
  27991. Primitives.Torus = Torus;
  27992. var Ground = (function (_super) {
  27993. __extends(Ground, _super);
  27994. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27996. _this.width = width;
  27997. _this.height = height;
  27998. _this.subdivisions = subdivisions;
  27999. return _this;
  28000. }
  28001. Ground.prototype._regenerateVertexData = function () {
  28002. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28003. };
  28004. Ground.prototype.copy = function (id) {
  28005. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28006. };
  28007. Ground.prototype.serialize = function () {
  28008. var serializationObject = _super.prototype.serialize.call(this);
  28009. serializationObject.width = this.width;
  28010. serializationObject.height = this.height;
  28011. serializationObject.subdivisions = this.subdivisions;
  28012. return serializationObject;
  28013. };
  28014. Ground.Parse = function (parsedGround, scene) {
  28015. if (scene.getGeometryByID(parsedGround.id)) {
  28016. return null; // null since geometry could be something else than a ground...
  28017. }
  28018. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28019. if (BABYLON.Tags) {
  28020. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28021. }
  28022. scene.pushGeometry(ground, true);
  28023. return ground;
  28024. };
  28025. return Ground;
  28026. }(_Primitive));
  28027. Primitives.Ground = Ground;
  28028. var TiledGround = (function (_super) {
  28029. __extends(TiledGround, _super);
  28030. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28031. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28032. _this.xmin = xmin;
  28033. _this.zmin = zmin;
  28034. _this.xmax = xmax;
  28035. _this.zmax = zmax;
  28036. _this.subdivisions = subdivisions;
  28037. _this.precision = precision;
  28038. return _this;
  28039. }
  28040. TiledGround.prototype._regenerateVertexData = function () {
  28041. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28042. };
  28043. TiledGround.prototype.copy = function (id) {
  28044. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28045. };
  28046. return TiledGround;
  28047. }(_Primitive));
  28048. Primitives.TiledGround = TiledGround;
  28049. var Plane = (function (_super) {
  28050. __extends(Plane, _super);
  28051. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28052. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28053. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28054. _this.size = size;
  28055. _this.side = side;
  28056. return _this;
  28057. }
  28058. Plane.prototype._regenerateVertexData = function () {
  28059. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28060. };
  28061. Plane.prototype.copy = function (id) {
  28062. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28063. };
  28064. Plane.prototype.serialize = function () {
  28065. var serializationObject = _super.prototype.serialize.call(this);
  28066. serializationObject.size = this.size;
  28067. return serializationObject;
  28068. };
  28069. Plane.Parse = function (parsedPlane, scene) {
  28070. if (scene.getGeometryByID(parsedPlane.id)) {
  28071. return null; // null since geometry could be something else than a ground...
  28072. }
  28073. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28074. if (BABYLON.Tags) {
  28075. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28076. }
  28077. scene.pushGeometry(plane, true);
  28078. return plane;
  28079. };
  28080. return Plane;
  28081. }(_Primitive));
  28082. Primitives.Plane = Plane;
  28083. var TorusKnot = (function (_super) {
  28084. __extends(TorusKnot, _super);
  28085. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28086. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28087. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28088. _this.radius = radius;
  28089. _this.tube = tube;
  28090. _this.radialSegments = radialSegments;
  28091. _this.tubularSegments = tubularSegments;
  28092. _this.p = p;
  28093. _this.q = q;
  28094. _this.side = side;
  28095. return _this;
  28096. }
  28097. TorusKnot.prototype._regenerateVertexData = function () {
  28098. 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 });
  28099. };
  28100. TorusKnot.prototype.copy = function (id) {
  28101. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28102. };
  28103. TorusKnot.prototype.serialize = function () {
  28104. var serializationObject = _super.prototype.serialize.call(this);
  28105. serializationObject.radius = this.radius;
  28106. serializationObject.tube = this.tube;
  28107. serializationObject.radialSegments = this.radialSegments;
  28108. serializationObject.tubularSegments = this.tubularSegments;
  28109. serializationObject.p = this.p;
  28110. serializationObject.q = this.q;
  28111. return serializationObject;
  28112. };
  28113. ;
  28114. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28115. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28116. return null; // null since geometry could be something else than a ground...
  28117. }
  28118. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28119. if (BABYLON.Tags) {
  28120. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28121. }
  28122. scene.pushGeometry(torusKnot, true);
  28123. return torusKnot;
  28124. };
  28125. return TorusKnot;
  28126. }(_Primitive));
  28127. Primitives.TorusKnot = TorusKnot;
  28128. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28129. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28130. })(BABYLON || (BABYLON = {}));
  28131. //# sourceMappingURL=babylon.geometry.js.map
  28132. var BABYLON;
  28133. (function (BABYLON) {
  28134. var PostProcessManager = (function () {
  28135. function PostProcessManager(scene) {
  28136. this._vertexBuffers = {};
  28137. this._scene = scene;
  28138. }
  28139. PostProcessManager.prototype._prepareBuffers = function () {
  28140. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28141. return;
  28142. }
  28143. // VBO
  28144. var vertices = [];
  28145. vertices.push(1, 1);
  28146. vertices.push(-1, 1);
  28147. vertices.push(-1, -1);
  28148. vertices.push(1, -1);
  28149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28150. // Indices
  28151. var indices = [];
  28152. indices.push(0);
  28153. indices.push(1);
  28154. indices.push(2);
  28155. indices.push(0);
  28156. indices.push(2);
  28157. indices.push(3);
  28158. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28159. };
  28160. // Methods
  28161. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28162. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28163. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28164. return false;
  28165. }
  28166. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28167. return true;
  28168. };
  28169. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28170. var engine = this._scene.getEngine();
  28171. for (var index = 0; index < postProcesses.length; index++) {
  28172. if (index < postProcesses.length - 1) {
  28173. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28174. }
  28175. else {
  28176. if (targetTexture) {
  28177. engine.bindFramebuffer(targetTexture);
  28178. }
  28179. else {
  28180. engine.restoreDefaultFramebuffer();
  28181. }
  28182. }
  28183. var pp = postProcesses[index];
  28184. var effect = pp.apply();
  28185. if (effect) {
  28186. pp.onBeforeRenderObservable.notifyObservers(effect);
  28187. // VBOs
  28188. this._prepareBuffers();
  28189. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28190. // Draw order
  28191. engine.draw(true, 0, 6);
  28192. pp.onAfterRenderObservable.notifyObservers(effect);
  28193. }
  28194. }
  28195. // Restore depth buffer
  28196. engine.setDepthBuffer(true);
  28197. engine.setDepthWrite(true);
  28198. };
  28199. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28200. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28201. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28202. return;
  28203. }
  28204. var engine = this._scene.getEngine();
  28205. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28206. if (index < len - 1) {
  28207. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28208. }
  28209. else {
  28210. if (targetTexture) {
  28211. engine.bindFramebuffer(targetTexture, faceIndex);
  28212. }
  28213. else {
  28214. engine.restoreDefaultFramebuffer();
  28215. }
  28216. }
  28217. if (doNotPresent) {
  28218. break;
  28219. }
  28220. var pp = postProcesses[index];
  28221. var effect = pp.apply();
  28222. if (effect) {
  28223. pp.onBeforeRenderObservable.notifyObservers(effect);
  28224. // VBOs
  28225. this._prepareBuffers();
  28226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28227. // Draw order
  28228. engine.draw(true, 0, 6);
  28229. pp.onAfterRenderObservable.notifyObservers(effect);
  28230. }
  28231. }
  28232. // Restore states
  28233. engine.setDepthBuffer(true);
  28234. engine.setDepthWrite(true);
  28235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28236. };
  28237. PostProcessManager.prototype.dispose = function () {
  28238. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28239. if (buffer) {
  28240. buffer.dispose();
  28241. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28242. }
  28243. if (this._indexBuffer) {
  28244. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28245. this._indexBuffer = null;
  28246. }
  28247. };
  28248. return PostProcessManager;
  28249. }());
  28250. BABYLON.PostProcessManager = PostProcessManager;
  28251. })(BABYLON || (BABYLON = {}));
  28252. //# sourceMappingURL=babylon.postProcessManager.js.map
  28253. var BABYLON;
  28254. (function (BABYLON) {
  28255. var AnimationRange = (function () {
  28256. function AnimationRange(name, from, to) {
  28257. this.name = name;
  28258. this.from = from;
  28259. this.to = to;
  28260. }
  28261. AnimationRange.prototype.clone = function () {
  28262. return new AnimationRange(this.name, this.from, this.to);
  28263. };
  28264. return AnimationRange;
  28265. }());
  28266. BABYLON.AnimationRange = AnimationRange;
  28267. /**
  28268. * Composed of a frame, and an action function
  28269. */
  28270. var AnimationEvent = (function () {
  28271. function AnimationEvent(frame, action, onlyOnce) {
  28272. this.frame = frame;
  28273. this.action = action;
  28274. this.onlyOnce = onlyOnce;
  28275. this.isDone = false;
  28276. }
  28277. return AnimationEvent;
  28278. }());
  28279. BABYLON.AnimationEvent = AnimationEvent;
  28280. var PathCursor = (function () {
  28281. function PathCursor(path) {
  28282. this.path = path;
  28283. this._onchange = new Array();
  28284. this.value = 0;
  28285. this.animations = new Array();
  28286. }
  28287. PathCursor.prototype.getPoint = function () {
  28288. var point = this.path.getPointAtLengthPosition(this.value);
  28289. return new BABYLON.Vector3(point.x, 0, point.y);
  28290. };
  28291. PathCursor.prototype.moveAhead = function (step) {
  28292. if (step === void 0) { step = 0.002; }
  28293. this.move(step);
  28294. return this;
  28295. };
  28296. PathCursor.prototype.moveBack = function (step) {
  28297. if (step === void 0) { step = 0.002; }
  28298. this.move(-step);
  28299. return this;
  28300. };
  28301. PathCursor.prototype.move = function (step) {
  28302. if (Math.abs(step) > 1) {
  28303. throw "step size should be less than 1.";
  28304. }
  28305. this.value += step;
  28306. this.ensureLimits();
  28307. this.raiseOnChange();
  28308. return this;
  28309. };
  28310. PathCursor.prototype.ensureLimits = function () {
  28311. while (this.value > 1) {
  28312. this.value -= 1;
  28313. }
  28314. while (this.value < 0) {
  28315. this.value += 1;
  28316. }
  28317. return this;
  28318. };
  28319. // used by animation engine
  28320. PathCursor.prototype.markAsDirty = function (propertyName) {
  28321. this.ensureLimits();
  28322. this.raiseOnChange();
  28323. return this;
  28324. };
  28325. PathCursor.prototype.raiseOnChange = function () {
  28326. var _this = this;
  28327. this._onchange.forEach(function (f) { return f(_this); });
  28328. return this;
  28329. };
  28330. PathCursor.prototype.onchange = function (f) {
  28331. this._onchange.push(f);
  28332. return this;
  28333. };
  28334. return PathCursor;
  28335. }());
  28336. BABYLON.PathCursor = PathCursor;
  28337. var Animation = (function () {
  28338. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28339. this.name = name;
  28340. this.targetProperty = targetProperty;
  28341. this.framePerSecond = framePerSecond;
  28342. this.dataType = dataType;
  28343. this.loopMode = loopMode;
  28344. this.enableBlending = enableBlending;
  28345. this._offsetsCache = {};
  28346. this._highLimitsCache = {};
  28347. this._stopped = false;
  28348. this._blendingFactor = 0;
  28349. // The set of event that will be linked to this animation
  28350. this._events = new Array();
  28351. this.allowMatricesInterpolation = false;
  28352. this.blendingSpeed = 0.01;
  28353. this._ranges = {};
  28354. this.targetPropertyPath = targetProperty.split(".");
  28355. this.dataType = dataType;
  28356. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28357. }
  28358. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28359. var dataType = undefined;
  28360. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28361. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28362. }
  28363. else if (from instanceof BABYLON.Quaternion) {
  28364. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28365. }
  28366. else if (from instanceof BABYLON.Vector3) {
  28367. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28368. }
  28369. else if (from instanceof BABYLON.Vector2) {
  28370. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28371. }
  28372. else if (from instanceof BABYLON.Color3) {
  28373. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28374. }
  28375. else if (from instanceof BABYLON.Size) {
  28376. dataType = Animation.ANIMATIONTYPE_SIZE;
  28377. }
  28378. if (dataType == undefined) {
  28379. return null;
  28380. }
  28381. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28382. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28383. animation.setKeys(keys);
  28384. if (easingFunction !== undefined) {
  28385. animation.setEasingFunction(easingFunction);
  28386. }
  28387. return animation;
  28388. };
  28389. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28390. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28391. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28392. };
  28393. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28394. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28395. node.animations.push(animation);
  28396. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28397. };
  28398. // Methods
  28399. /**
  28400. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28401. */
  28402. Animation.prototype.toString = function (fullDetails) {
  28403. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28404. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28405. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28406. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28407. if (fullDetails) {
  28408. ret += ", Ranges: {";
  28409. var first = true;
  28410. for (var name in this._ranges) {
  28411. if (first) {
  28412. ret += ", ";
  28413. first = false;
  28414. }
  28415. ret += name;
  28416. }
  28417. ret += "}";
  28418. }
  28419. return ret;
  28420. };
  28421. /**
  28422. * Add an event to this animation.
  28423. */
  28424. Animation.prototype.addEvent = function (event) {
  28425. this._events.push(event);
  28426. };
  28427. /**
  28428. * Remove all events found at the given frame
  28429. * @param frame
  28430. */
  28431. Animation.prototype.removeEvents = function (frame) {
  28432. for (var index = 0; index < this._events.length; index++) {
  28433. if (this._events[index].frame === frame) {
  28434. this._events.splice(index, 1);
  28435. index--;
  28436. }
  28437. }
  28438. };
  28439. Animation.prototype.createRange = function (name, from, to) {
  28440. // check name not already in use; could happen for bones after serialized
  28441. if (!this._ranges[name]) {
  28442. this._ranges[name] = new AnimationRange(name, from, to);
  28443. }
  28444. };
  28445. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28446. if (deleteFrames === void 0) { deleteFrames = true; }
  28447. if (this._ranges[name]) {
  28448. if (deleteFrames) {
  28449. var from = this._ranges[name].from;
  28450. var to = this._ranges[name].to;
  28451. // this loop MUST go high to low for multiple splices to work
  28452. for (var key = this._keys.length - 1; key >= 0; key--) {
  28453. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28454. this._keys.splice(key, 1);
  28455. }
  28456. }
  28457. }
  28458. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28459. }
  28460. };
  28461. Animation.prototype.getRange = function (name) {
  28462. return this._ranges[name];
  28463. };
  28464. Animation.prototype.reset = function () {
  28465. this._offsetsCache = {};
  28466. this._highLimitsCache = {};
  28467. this.currentFrame = 0;
  28468. this._blendingFactor = 0;
  28469. this._originalBlendValue = null;
  28470. };
  28471. Animation.prototype.isStopped = function () {
  28472. return this._stopped;
  28473. };
  28474. Animation.prototype.getKeys = function () {
  28475. return this._keys;
  28476. };
  28477. Animation.prototype.getHighestFrame = function () {
  28478. var ret = 0;
  28479. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28480. if (ret < this._keys[key].frame) {
  28481. ret = this._keys[key].frame;
  28482. }
  28483. }
  28484. return ret;
  28485. };
  28486. Animation.prototype.getEasingFunction = function () {
  28487. return this._easingFunction;
  28488. };
  28489. Animation.prototype.setEasingFunction = function (easingFunction) {
  28490. this._easingFunction = easingFunction;
  28491. };
  28492. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28493. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  28494. };
  28495. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28496. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28497. };
  28498. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28499. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28500. };
  28501. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28502. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  28503. };
  28504. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28505. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28506. };
  28507. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28508. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28509. };
  28510. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28511. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28512. };
  28513. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28514. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28515. };
  28516. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28517. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28518. };
  28519. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28520. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28521. };
  28522. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28523. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28524. };
  28525. Animation.prototype.clone = function () {
  28526. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28527. clone.enableBlending = this.enableBlending;
  28528. clone.blendingSpeed = this.blendingSpeed;
  28529. if (this._keys) {
  28530. clone.setKeys(this._keys);
  28531. }
  28532. if (this._ranges) {
  28533. clone._ranges = {};
  28534. for (var name in this._ranges) {
  28535. clone._ranges[name] = this._ranges[name].clone();
  28536. }
  28537. }
  28538. return clone;
  28539. };
  28540. Animation.prototype.setKeys = function (values) {
  28541. this._keys = values.slice(0);
  28542. this._offsetsCache = {};
  28543. this._highLimitsCache = {};
  28544. };
  28545. Animation.prototype._getKeyValue = function (value) {
  28546. if (typeof value === "function") {
  28547. return value();
  28548. }
  28549. return value;
  28550. };
  28551. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28552. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28553. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28554. }
  28555. this.currentFrame = currentFrame;
  28556. // Try to get a hash to find the right key
  28557. 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));
  28558. if (this._keys[startKeyIndex].frame >= currentFrame) {
  28559. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  28560. startKeyIndex--;
  28561. }
  28562. }
  28563. for (var key = startKeyIndex; key < this._keys.length; key++) {
  28564. var endKey = this._keys[key + 1];
  28565. if (endKey.frame >= currentFrame) {
  28566. var startKey = this._keys[key];
  28567. var startValue = this._getKeyValue(startKey.value);
  28568. var endValue = this._getKeyValue(endKey.value);
  28569. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  28570. var frameDelta = endKey.frame - startKey.frame;
  28571. // gradient : percent of currentFrame between the frame inf and the frame sup
  28572. var gradient = (currentFrame - startKey.frame) / frameDelta;
  28573. // check for easingFunction and correction of gradient
  28574. if (this._easingFunction != null) {
  28575. gradient = this._easingFunction.ease(gradient);
  28576. }
  28577. switch (this.dataType) {
  28578. // Float
  28579. case Animation.ANIMATIONTYPE_FLOAT:
  28580. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  28581. switch (loopMode) {
  28582. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28583. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28584. return floatValue;
  28585. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28586. return offsetValue * repeatCount + floatValue;
  28587. }
  28588. break;
  28589. // Quaternion
  28590. case Animation.ANIMATIONTYPE_QUATERNION:
  28591. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28592. switch (loopMode) {
  28593. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28594. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28595. return quatValue;
  28596. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28597. return quatValue.add(offsetValue.scale(repeatCount));
  28598. }
  28599. return quatValue;
  28600. // Vector3
  28601. case Animation.ANIMATIONTYPE_VECTOR3:
  28602. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  28603. switch (loopMode) {
  28604. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28605. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28606. return vec3Value;
  28607. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28608. return vec3Value.add(offsetValue.scale(repeatCount));
  28609. }
  28610. // Vector2
  28611. case Animation.ANIMATIONTYPE_VECTOR2:
  28612. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  28613. switch (loopMode) {
  28614. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28615. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28616. return vec2Value;
  28617. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28618. return vec2Value.add(offsetValue.scale(repeatCount));
  28619. }
  28620. // Size
  28621. case Animation.ANIMATIONTYPE_SIZE:
  28622. switch (loopMode) {
  28623. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28624. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28625. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28626. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28627. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28628. }
  28629. // Color3
  28630. case Animation.ANIMATIONTYPE_COLOR3:
  28631. switch (loopMode) {
  28632. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28633. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28634. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28635. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28636. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28637. }
  28638. // Matrix
  28639. case Animation.ANIMATIONTYPE_MATRIX:
  28640. switch (loopMode) {
  28641. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28642. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28643. if (this.allowMatricesInterpolation) {
  28644. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28645. }
  28646. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28647. return startValue;
  28648. }
  28649. default:
  28650. break;
  28651. }
  28652. break;
  28653. }
  28654. }
  28655. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28656. };
  28657. Animation.prototype.setValue = function (currentValue, blend) {
  28658. if (blend === void 0) { blend = false; }
  28659. // Set value
  28660. var path;
  28661. var destination;
  28662. if (this.targetPropertyPath.length > 1) {
  28663. var property = this._target[this.targetPropertyPath[0]];
  28664. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28665. property = property[this.targetPropertyPath[index]];
  28666. }
  28667. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28668. destination = property;
  28669. }
  28670. else {
  28671. path = this.targetPropertyPath[0];
  28672. destination = this._target;
  28673. }
  28674. // Blending
  28675. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28676. if (!this._originalBlendValue) {
  28677. if (destination[path].clone) {
  28678. this._originalBlendValue = destination[path].clone();
  28679. }
  28680. else {
  28681. this._originalBlendValue = destination[path];
  28682. }
  28683. }
  28684. if (this._originalBlendValue.prototype) {
  28685. if (this._originalBlendValue.prototype.Lerp) {
  28686. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28687. }
  28688. else {
  28689. destination[path] = currentValue;
  28690. }
  28691. }
  28692. else if (this._originalBlendValue.m) {
  28693. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28694. }
  28695. else {
  28696. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28697. }
  28698. this._blendingFactor += this.blendingSpeed;
  28699. }
  28700. else {
  28701. destination[path] = currentValue;
  28702. }
  28703. if (this._target.markAsDirty) {
  28704. this._target.markAsDirty(this.targetProperty);
  28705. }
  28706. };
  28707. Animation.prototype.goToFrame = function (frame) {
  28708. if (frame < this._keys[0].frame) {
  28709. frame = this._keys[0].frame;
  28710. }
  28711. else if (frame > this._keys[this._keys.length - 1].frame) {
  28712. frame = this._keys[this._keys.length - 1].frame;
  28713. }
  28714. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28715. this.setValue(currentValue);
  28716. };
  28717. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28718. if (blend === void 0) { blend = false; }
  28719. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28720. this._stopped = true;
  28721. return false;
  28722. }
  28723. var returnValue = true;
  28724. // Adding a start key at frame 0 if missing
  28725. if (this._keys[0].frame !== 0) {
  28726. var newKey = { frame: 0, value: this._keys[0].value };
  28727. this._keys.splice(0, 0, newKey);
  28728. }
  28729. // Check limits
  28730. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28731. from = this._keys[0].frame;
  28732. }
  28733. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28734. to = this._keys[this._keys.length - 1].frame;
  28735. }
  28736. //to and from cannot be the same key
  28737. if (from === to) {
  28738. from++;
  28739. }
  28740. // Compute ratio
  28741. var range = to - from;
  28742. var offsetValue;
  28743. // ratio represents the frame delta between from and to
  28744. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28745. var highLimitValue = 0;
  28746. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  28747. returnValue = false;
  28748. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28749. }
  28750. else {
  28751. // Get max value if required
  28752. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28753. var keyOffset = to.toString() + from.toString();
  28754. if (!this._offsetsCache[keyOffset]) {
  28755. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28756. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28757. switch (this.dataType) {
  28758. // Float
  28759. case Animation.ANIMATIONTYPE_FLOAT:
  28760. this._offsetsCache[keyOffset] = toValue - fromValue;
  28761. break;
  28762. // Quaternion
  28763. case Animation.ANIMATIONTYPE_QUATERNION:
  28764. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28765. break;
  28766. // Vector3
  28767. case Animation.ANIMATIONTYPE_VECTOR3:
  28768. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28769. // Vector2
  28770. case Animation.ANIMATIONTYPE_VECTOR2:
  28771. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28772. // Size
  28773. case Animation.ANIMATIONTYPE_SIZE:
  28774. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28775. // Color3
  28776. case Animation.ANIMATIONTYPE_COLOR3:
  28777. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28778. default:
  28779. break;
  28780. }
  28781. this._highLimitsCache[keyOffset] = toValue;
  28782. }
  28783. highLimitValue = this._highLimitsCache[keyOffset];
  28784. offsetValue = this._offsetsCache[keyOffset];
  28785. }
  28786. }
  28787. if (offsetValue === undefined) {
  28788. switch (this.dataType) {
  28789. // Float
  28790. case Animation.ANIMATIONTYPE_FLOAT:
  28791. offsetValue = 0;
  28792. break;
  28793. // Quaternion
  28794. case Animation.ANIMATIONTYPE_QUATERNION:
  28795. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28796. break;
  28797. // Vector3
  28798. case Animation.ANIMATIONTYPE_VECTOR3:
  28799. offsetValue = BABYLON.Vector3.Zero();
  28800. break;
  28801. // Vector2
  28802. case Animation.ANIMATIONTYPE_VECTOR2:
  28803. offsetValue = BABYLON.Vector2.Zero();
  28804. break;
  28805. // Size
  28806. case Animation.ANIMATIONTYPE_SIZE:
  28807. offsetValue = BABYLON.Size.Zero();
  28808. break;
  28809. // Color3
  28810. case Animation.ANIMATIONTYPE_COLOR3:
  28811. offsetValue = BABYLON.Color3.Black();
  28812. }
  28813. }
  28814. // Compute value
  28815. var repeatCount = (ratio / range) >> 0;
  28816. var currentFrame = returnValue ? from + ratio % range : to;
  28817. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28818. // Set value
  28819. this.setValue(currentValue);
  28820. // Check events
  28821. for (var index = 0; index < this._events.length; index++) {
  28822. if (currentFrame >= this._events[index].frame) {
  28823. var event = this._events[index];
  28824. if (!event.isDone) {
  28825. // If event should be done only once, remove it.
  28826. if (event.onlyOnce) {
  28827. this._events.splice(index, 1);
  28828. index--;
  28829. }
  28830. event.isDone = true;
  28831. event.action();
  28832. } // Don't do anything if the event has already be done.
  28833. }
  28834. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28835. // reset event, the animation is looping
  28836. this._events[index].isDone = false;
  28837. }
  28838. }
  28839. if (!returnValue) {
  28840. this._stopped = true;
  28841. }
  28842. return returnValue;
  28843. };
  28844. Animation.prototype.serialize = function () {
  28845. var serializationObject = {};
  28846. serializationObject.name = this.name;
  28847. serializationObject.property = this.targetProperty;
  28848. serializationObject.framePerSecond = this.framePerSecond;
  28849. serializationObject.dataType = this.dataType;
  28850. serializationObject.loopBehavior = this.loopMode;
  28851. serializationObject.enableBlending = this.enableBlending;
  28852. serializationObject.blendingSpeed = this.blendingSpeed;
  28853. var dataType = this.dataType;
  28854. serializationObject.keys = [];
  28855. var keys = this.getKeys();
  28856. for (var index = 0; index < keys.length; index++) {
  28857. var animationKey = keys[index];
  28858. var key = {};
  28859. key.frame = animationKey.frame;
  28860. switch (dataType) {
  28861. case Animation.ANIMATIONTYPE_FLOAT:
  28862. key.values = [animationKey.value];
  28863. break;
  28864. case Animation.ANIMATIONTYPE_QUATERNION:
  28865. case Animation.ANIMATIONTYPE_MATRIX:
  28866. case Animation.ANIMATIONTYPE_VECTOR3:
  28867. case Animation.ANIMATIONTYPE_COLOR3:
  28868. key.values = animationKey.value.asArray();
  28869. break;
  28870. }
  28871. serializationObject.keys.push(key);
  28872. }
  28873. serializationObject.ranges = [];
  28874. for (var name in this._ranges) {
  28875. var range = {};
  28876. range.name = name;
  28877. range.from = this._ranges[name].from;
  28878. range.to = this._ranges[name].to;
  28879. serializationObject.ranges.push(range);
  28880. }
  28881. return serializationObject;
  28882. };
  28883. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28884. get: function () {
  28885. return Animation._ANIMATIONTYPE_FLOAT;
  28886. },
  28887. enumerable: true,
  28888. configurable: true
  28889. });
  28890. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28891. get: function () {
  28892. return Animation._ANIMATIONTYPE_VECTOR3;
  28893. },
  28894. enumerable: true,
  28895. configurable: true
  28896. });
  28897. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28898. get: function () {
  28899. return Animation._ANIMATIONTYPE_VECTOR2;
  28900. },
  28901. enumerable: true,
  28902. configurable: true
  28903. });
  28904. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28905. get: function () {
  28906. return Animation._ANIMATIONTYPE_SIZE;
  28907. },
  28908. enumerable: true,
  28909. configurable: true
  28910. });
  28911. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28912. get: function () {
  28913. return Animation._ANIMATIONTYPE_QUATERNION;
  28914. },
  28915. enumerable: true,
  28916. configurable: true
  28917. });
  28918. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28919. get: function () {
  28920. return Animation._ANIMATIONTYPE_MATRIX;
  28921. },
  28922. enumerable: true,
  28923. configurable: true
  28924. });
  28925. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28926. get: function () {
  28927. return Animation._ANIMATIONTYPE_COLOR3;
  28928. },
  28929. enumerable: true,
  28930. configurable: true
  28931. });
  28932. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28933. get: function () {
  28934. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28935. },
  28936. enumerable: true,
  28937. configurable: true
  28938. });
  28939. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28940. get: function () {
  28941. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28942. },
  28943. enumerable: true,
  28944. configurable: true
  28945. });
  28946. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28947. get: function () {
  28948. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28949. },
  28950. enumerable: true,
  28951. configurable: true
  28952. });
  28953. Animation.Parse = function (parsedAnimation) {
  28954. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28955. var dataType = parsedAnimation.dataType;
  28956. var keys = [];
  28957. var data;
  28958. var index;
  28959. if (parsedAnimation.enableBlending) {
  28960. animation.enableBlending = parsedAnimation.enableBlending;
  28961. }
  28962. if (parsedAnimation.blendingSpeed) {
  28963. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  28964. }
  28965. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28966. var key = parsedAnimation.keys[index];
  28967. switch (dataType) {
  28968. case Animation.ANIMATIONTYPE_FLOAT:
  28969. data = key.values[0];
  28970. break;
  28971. case Animation.ANIMATIONTYPE_QUATERNION:
  28972. data = BABYLON.Quaternion.FromArray(key.values);
  28973. break;
  28974. case Animation.ANIMATIONTYPE_MATRIX:
  28975. data = BABYLON.Matrix.FromArray(key.values);
  28976. break;
  28977. case Animation.ANIMATIONTYPE_COLOR3:
  28978. data = BABYLON.Color3.FromArray(key.values);
  28979. break;
  28980. case Animation.ANIMATIONTYPE_VECTOR3:
  28981. default:
  28982. data = BABYLON.Vector3.FromArray(key.values);
  28983. break;
  28984. }
  28985. keys.push({
  28986. frame: key.frame,
  28987. value: data
  28988. });
  28989. }
  28990. animation.setKeys(keys);
  28991. if (parsedAnimation.ranges) {
  28992. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28993. data = parsedAnimation.ranges[index];
  28994. animation.createRange(data.name, data.from, data.to);
  28995. }
  28996. }
  28997. return animation;
  28998. };
  28999. Animation.AppendSerializedAnimations = function (source, destination) {
  29000. if (source.animations) {
  29001. destination.animations = [];
  29002. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29003. var animation = source.animations[animationIndex];
  29004. destination.animations.push(animation.serialize());
  29005. }
  29006. }
  29007. };
  29008. return Animation;
  29009. }());
  29010. // Statics
  29011. Animation._ANIMATIONTYPE_FLOAT = 0;
  29012. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29013. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29014. Animation._ANIMATIONTYPE_MATRIX = 3;
  29015. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29016. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29017. Animation._ANIMATIONTYPE_SIZE = 6;
  29018. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29019. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29020. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29021. BABYLON.Animation = Animation;
  29022. })(BABYLON || (BABYLON = {}));
  29023. //# sourceMappingURL=babylon.animation.js.map
  29024. var BABYLON;
  29025. (function (BABYLON) {
  29026. var Animatable = (function () {
  29027. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29028. if (fromFrame === void 0) { fromFrame = 0; }
  29029. if (toFrame === void 0) { toFrame = 100; }
  29030. if (loopAnimation === void 0) { loopAnimation = false; }
  29031. if (speedRatio === void 0) { speedRatio = 1.0; }
  29032. this.target = target;
  29033. this.fromFrame = fromFrame;
  29034. this.toFrame = toFrame;
  29035. this.loopAnimation = loopAnimation;
  29036. this.speedRatio = speedRatio;
  29037. this.onAnimationEnd = onAnimationEnd;
  29038. this._localDelayOffset = null;
  29039. this._pausedDelay = null;
  29040. this._animations = new Array();
  29041. this._paused = false;
  29042. this.animationStarted = false;
  29043. if (animations) {
  29044. this.appendAnimations(target, animations);
  29045. }
  29046. this._scene = scene;
  29047. scene._activeAnimatables.push(this);
  29048. }
  29049. // Methods
  29050. Animatable.prototype.getAnimations = function () {
  29051. return this._animations;
  29052. };
  29053. Animatable.prototype.appendAnimations = function (target, animations) {
  29054. for (var index = 0; index < animations.length; index++) {
  29055. var animation = animations[index];
  29056. animation._target = target;
  29057. this._animations.push(animation);
  29058. }
  29059. };
  29060. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29061. var animations = this._animations;
  29062. for (var index = 0; index < animations.length; index++) {
  29063. if (animations[index].targetProperty === property) {
  29064. return animations[index];
  29065. }
  29066. }
  29067. return null;
  29068. };
  29069. Animatable.prototype.reset = function () {
  29070. var animations = this._animations;
  29071. for (var index = 0; index < animations.length; index++) {
  29072. animations[index].reset();
  29073. }
  29074. this._localDelayOffset = null;
  29075. this._pausedDelay = null;
  29076. };
  29077. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29078. var animations = this._animations;
  29079. for (var index = 0; index < animations.length; index++) {
  29080. animations[index].enableBlending = true;
  29081. animations[index].blendingSpeed = blendingSpeed;
  29082. }
  29083. };
  29084. Animatable.prototype.disableBlending = function () {
  29085. var animations = this._animations;
  29086. for (var index = 0; index < animations.length; index++) {
  29087. animations[index].enableBlending = false;
  29088. }
  29089. };
  29090. Animatable.prototype.goToFrame = function (frame) {
  29091. var animations = this._animations;
  29092. if (animations[0]) {
  29093. var fps = animations[0].framePerSecond;
  29094. var currentFrame = animations[0].currentFrame;
  29095. var adjustTime = frame - currentFrame;
  29096. var delay = adjustTime * 1000 / fps;
  29097. this._localDelayOffset -= delay;
  29098. }
  29099. for (var index = 0; index < animations.length; index++) {
  29100. animations[index].goToFrame(frame);
  29101. }
  29102. };
  29103. Animatable.prototype.pause = function () {
  29104. if (this._paused) {
  29105. return;
  29106. }
  29107. this._paused = true;
  29108. };
  29109. Animatable.prototype.restart = function () {
  29110. this._paused = false;
  29111. };
  29112. Animatable.prototype.stop = function (animationName) {
  29113. if (animationName) {
  29114. var idx = this._scene._activeAnimatables.indexOf(this);
  29115. if (idx > -1) {
  29116. var animations = this._animations;
  29117. for (var index = animations.length - 1; index >= 0; index--) {
  29118. if (typeof animationName === "string" && animations[index].name != animationName) {
  29119. continue;
  29120. }
  29121. animations[index].reset();
  29122. animations.splice(index, 1);
  29123. }
  29124. if (animations.length == 0) {
  29125. this._scene._activeAnimatables.splice(idx, 1);
  29126. if (this.onAnimationEnd) {
  29127. this.onAnimationEnd();
  29128. }
  29129. }
  29130. }
  29131. }
  29132. else {
  29133. var index = this._scene._activeAnimatables.indexOf(this);
  29134. if (index > -1) {
  29135. this._scene._activeAnimatables.splice(index, 1);
  29136. var animations = this._animations;
  29137. for (var index = 0; index < animations.length; index++) {
  29138. animations[index].reset();
  29139. }
  29140. if (this.onAnimationEnd) {
  29141. this.onAnimationEnd();
  29142. }
  29143. }
  29144. }
  29145. };
  29146. Animatable.prototype._animate = function (delay) {
  29147. if (this._paused) {
  29148. this.animationStarted = false;
  29149. if (this._pausedDelay === null) {
  29150. this._pausedDelay = delay;
  29151. }
  29152. return true;
  29153. }
  29154. if (this._localDelayOffset === null) {
  29155. this._localDelayOffset = delay;
  29156. }
  29157. else if (this._pausedDelay !== null) {
  29158. this._localDelayOffset += delay - this._pausedDelay;
  29159. this._pausedDelay = null;
  29160. }
  29161. // Animating
  29162. var running = false;
  29163. var animations = this._animations;
  29164. var index;
  29165. for (index = 0; index < animations.length; index++) {
  29166. var animation = animations[index];
  29167. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29168. running = running || isRunning;
  29169. }
  29170. this.animationStarted = running;
  29171. if (!running) {
  29172. // Remove from active animatables
  29173. index = this._scene._activeAnimatables.indexOf(this);
  29174. this._scene._activeAnimatables.splice(index, 1);
  29175. }
  29176. if (!running && this.onAnimationEnd) {
  29177. this.onAnimationEnd();
  29178. this.onAnimationEnd = null;
  29179. }
  29180. return running;
  29181. };
  29182. return Animatable;
  29183. }());
  29184. BABYLON.Animatable = Animatable;
  29185. })(BABYLON || (BABYLON = {}));
  29186. //# sourceMappingURL=babylon.animatable.js.map
  29187. var BABYLON;
  29188. (function (BABYLON) {
  29189. var EasingFunction = (function () {
  29190. function EasingFunction() {
  29191. // Properties
  29192. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29193. }
  29194. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29195. get: function () {
  29196. return EasingFunction._EASINGMODE_EASEIN;
  29197. },
  29198. enumerable: true,
  29199. configurable: true
  29200. });
  29201. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29202. get: function () {
  29203. return EasingFunction._EASINGMODE_EASEOUT;
  29204. },
  29205. enumerable: true,
  29206. configurable: true
  29207. });
  29208. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29209. get: function () {
  29210. return EasingFunction._EASINGMODE_EASEINOUT;
  29211. },
  29212. enumerable: true,
  29213. configurable: true
  29214. });
  29215. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29216. var n = Math.min(Math.max(easingMode, 0), 2);
  29217. this._easingMode = n;
  29218. };
  29219. EasingFunction.prototype.getEasingMode = function () {
  29220. return this._easingMode;
  29221. };
  29222. EasingFunction.prototype.easeInCore = function (gradient) {
  29223. throw new Error('You must implement this method');
  29224. };
  29225. EasingFunction.prototype.ease = function (gradient) {
  29226. switch (this._easingMode) {
  29227. case EasingFunction.EASINGMODE_EASEIN:
  29228. return this.easeInCore(gradient);
  29229. case EasingFunction.EASINGMODE_EASEOUT:
  29230. return (1 - this.easeInCore(1 - gradient));
  29231. }
  29232. if (gradient >= 0.5) {
  29233. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29234. }
  29235. return (this.easeInCore(gradient * 2) * 0.5);
  29236. };
  29237. return EasingFunction;
  29238. }());
  29239. //Statics
  29240. EasingFunction._EASINGMODE_EASEIN = 0;
  29241. EasingFunction._EASINGMODE_EASEOUT = 1;
  29242. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29243. BABYLON.EasingFunction = EasingFunction;
  29244. var CircleEase = (function (_super) {
  29245. __extends(CircleEase, _super);
  29246. function CircleEase() {
  29247. return _super !== null && _super.apply(this, arguments) || this;
  29248. }
  29249. CircleEase.prototype.easeInCore = function (gradient) {
  29250. gradient = Math.max(0, Math.min(1, gradient));
  29251. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29252. };
  29253. return CircleEase;
  29254. }(EasingFunction));
  29255. BABYLON.CircleEase = CircleEase;
  29256. var BackEase = (function (_super) {
  29257. __extends(BackEase, _super);
  29258. function BackEase(amplitude) {
  29259. if (amplitude === void 0) { amplitude = 1; }
  29260. var _this = _super.call(this) || this;
  29261. _this.amplitude = amplitude;
  29262. return _this;
  29263. }
  29264. BackEase.prototype.easeInCore = function (gradient) {
  29265. var num = Math.max(0, this.amplitude);
  29266. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29267. };
  29268. return BackEase;
  29269. }(EasingFunction));
  29270. BABYLON.BackEase = BackEase;
  29271. var BounceEase = (function (_super) {
  29272. __extends(BounceEase, _super);
  29273. function BounceEase(bounces, bounciness) {
  29274. if (bounces === void 0) { bounces = 3; }
  29275. if (bounciness === void 0) { bounciness = 2; }
  29276. var _this = _super.call(this) || this;
  29277. _this.bounces = bounces;
  29278. _this.bounciness = bounciness;
  29279. return _this;
  29280. }
  29281. BounceEase.prototype.easeInCore = function (gradient) {
  29282. var y = Math.max(0.0, this.bounces);
  29283. var bounciness = this.bounciness;
  29284. if (bounciness <= 1.0) {
  29285. bounciness = 1.001;
  29286. }
  29287. var num9 = Math.pow(bounciness, y);
  29288. var num5 = 1.0 - bounciness;
  29289. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29290. var num15 = gradient * num4;
  29291. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29292. var num3 = Math.floor(num65);
  29293. var num13 = num3 + 1.0;
  29294. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29295. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29296. var num7 = (num8 + num12) * 0.5;
  29297. var num6 = gradient - num7;
  29298. var num2 = num7 - num8;
  29299. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29300. };
  29301. return BounceEase;
  29302. }(EasingFunction));
  29303. BABYLON.BounceEase = BounceEase;
  29304. var CubicEase = (function (_super) {
  29305. __extends(CubicEase, _super);
  29306. function CubicEase() {
  29307. return _super !== null && _super.apply(this, arguments) || this;
  29308. }
  29309. CubicEase.prototype.easeInCore = function (gradient) {
  29310. return (gradient * gradient * gradient);
  29311. };
  29312. return CubicEase;
  29313. }(EasingFunction));
  29314. BABYLON.CubicEase = CubicEase;
  29315. var ElasticEase = (function (_super) {
  29316. __extends(ElasticEase, _super);
  29317. function ElasticEase(oscillations, springiness) {
  29318. if (oscillations === void 0) { oscillations = 3; }
  29319. if (springiness === void 0) { springiness = 3; }
  29320. var _this = _super.call(this) || this;
  29321. _this.oscillations = oscillations;
  29322. _this.springiness = springiness;
  29323. return _this;
  29324. }
  29325. ElasticEase.prototype.easeInCore = function (gradient) {
  29326. var num2;
  29327. var num3 = Math.max(0.0, this.oscillations);
  29328. var num = Math.max(0.0, this.springiness);
  29329. if (num == 0) {
  29330. num2 = gradient;
  29331. }
  29332. else {
  29333. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29334. }
  29335. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29336. };
  29337. return ElasticEase;
  29338. }(EasingFunction));
  29339. BABYLON.ElasticEase = ElasticEase;
  29340. var ExponentialEase = (function (_super) {
  29341. __extends(ExponentialEase, _super);
  29342. function ExponentialEase(exponent) {
  29343. if (exponent === void 0) { exponent = 2; }
  29344. var _this = _super.call(this) || this;
  29345. _this.exponent = exponent;
  29346. return _this;
  29347. }
  29348. ExponentialEase.prototype.easeInCore = function (gradient) {
  29349. if (this.exponent <= 0) {
  29350. return gradient;
  29351. }
  29352. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29353. };
  29354. return ExponentialEase;
  29355. }(EasingFunction));
  29356. BABYLON.ExponentialEase = ExponentialEase;
  29357. var PowerEase = (function (_super) {
  29358. __extends(PowerEase, _super);
  29359. function PowerEase(power) {
  29360. if (power === void 0) { power = 2; }
  29361. var _this = _super.call(this) || this;
  29362. _this.power = power;
  29363. return _this;
  29364. }
  29365. PowerEase.prototype.easeInCore = function (gradient) {
  29366. var y = Math.max(0.0, this.power);
  29367. return Math.pow(gradient, y);
  29368. };
  29369. return PowerEase;
  29370. }(EasingFunction));
  29371. BABYLON.PowerEase = PowerEase;
  29372. var QuadraticEase = (function (_super) {
  29373. __extends(QuadraticEase, _super);
  29374. function QuadraticEase() {
  29375. return _super !== null && _super.apply(this, arguments) || this;
  29376. }
  29377. QuadraticEase.prototype.easeInCore = function (gradient) {
  29378. return (gradient * gradient);
  29379. };
  29380. return QuadraticEase;
  29381. }(EasingFunction));
  29382. BABYLON.QuadraticEase = QuadraticEase;
  29383. var QuarticEase = (function (_super) {
  29384. __extends(QuarticEase, _super);
  29385. function QuarticEase() {
  29386. return _super !== null && _super.apply(this, arguments) || this;
  29387. }
  29388. QuarticEase.prototype.easeInCore = function (gradient) {
  29389. return (gradient * gradient * gradient * gradient);
  29390. };
  29391. return QuarticEase;
  29392. }(EasingFunction));
  29393. BABYLON.QuarticEase = QuarticEase;
  29394. var QuinticEase = (function (_super) {
  29395. __extends(QuinticEase, _super);
  29396. function QuinticEase() {
  29397. return _super !== null && _super.apply(this, arguments) || this;
  29398. }
  29399. QuinticEase.prototype.easeInCore = function (gradient) {
  29400. return (gradient * gradient * gradient * gradient * gradient);
  29401. };
  29402. return QuinticEase;
  29403. }(EasingFunction));
  29404. BABYLON.QuinticEase = QuinticEase;
  29405. var SineEase = (function (_super) {
  29406. __extends(SineEase, _super);
  29407. function SineEase() {
  29408. return _super !== null && _super.apply(this, arguments) || this;
  29409. }
  29410. SineEase.prototype.easeInCore = function (gradient) {
  29411. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29412. };
  29413. return SineEase;
  29414. }(EasingFunction));
  29415. BABYLON.SineEase = SineEase;
  29416. var BezierCurveEase = (function (_super) {
  29417. __extends(BezierCurveEase, _super);
  29418. function BezierCurveEase(x1, y1, x2, y2) {
  29419. if (x1 === void 0) { x1 = 0; }
  29420. if (y1 === void 0) { y1 = 0; }
  29421. if (x2 === void 0) { x2 = 1; }
  29422. if (y2 === void 0) { y2 = 1; }
  29423. var _this = _super.call(this) || this;
  29424. _this.x1 = x1;
  29425. _this.y1 = y1;
  29426. _this.x2 = x2;
  29427. _this.y2 = y2;
  29428. return _this;
  29429. }
  29430. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29431. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29432. };
  29433. return BezierCurveEase;
  29434. }(EasingFunction));
  29435. BABYLON.BezierCurveEase = BezierCurveEase;
  29436. })(BABYLON || (BABYLON = {}));
  29437. //# sourceMappingURL=babylon.easing.js.map
  29438. var BABYLON;
  29439. (function (BABYLON) {
  29440. BABYLON.CameraInputTypes = {};
  29441. var CameraInputsManager = (function () {
  29442. function CameraInputsManager(camera) {
  29443. this.attached = {};
  29444. this.camera = camera;
  29445. this.checkInputs = function () { };
  29446. }
  29447. CameraInputsManager.prototype.add = function (input) {
  29448. var type = input.getSimpleName();
  29449. if (this.attached[type]) {
  29450. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29451. return;
  29452. }
  29453. this.attached[type] = input;
  29454. input.camera = this.camera;
  29455. //for checkInputs, we are dynamically creating a function
  29456. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29457. if (input.checkInputs) {
  29458. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29459. }
  29460. if (this.attachedElement) {
  29461. input.attachControl(this.attachedElement);
  29462. }
  29463. };
  29464. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29465. for (var cam in this.attached) {
  29466. var input = this.attached[cam];
  29467. if (input === inputToRemove) {
  29468. input.detachControl(this.attachedElement);
  29469. delete this.attached[cam];
  29470. this.rebuildInputCheck();
  29471. }
  29472. }
  29473. };
  29474. CameraInputsManager.prototype.removeByType = function (inputType) {
  29475. for (var cam in this.attached) {
  29476. var input = this.attached[cam];
  29477. if (input.getTypeName() === inputType) {
  29478. input.detachControl(this.attachedElement);
  29479. delete this.attached[cam];
  29480. this.rebuildInputCheck();
  29481. }
  29482. }
  29483. };
  29484. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29485. var current = this.checkInputs;
  29486. return function () {
  29487. current();
  29488. fn();
  29489. };
  29490. };
  29491. CameraInputsManager.prototype.attachInput = function (input) {
  29492. input.attachControl(this.attachedElement, this.noPreventDefault);
  29493. };
  29494. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29495. if (this.attachedElement) {
  29496. return;
  29497. }
  29498. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29499. this.attachedElement = element;
  29500. this.noPreventDefault = noPreventDefault;
  29501. for (var cam in this.attached) {
  29502. var input = this.attached[cam];
  29503. this.attached[cam].attachControl(element, noPreventDefault);
  29504. }
  29505. };
  29506. CameraInputsManager.prototype.detachElement = function (element) {
  29507. if (this.attachedElement !== element) {
  29508. return;
  29509. }
  29510. for (var cam in this.attached) {
  29511. var input = this.attached[cam];
  29512. this.attached[cam].detachControl(element);
  29513. }
  29514. this.attachedElement = null;
  29515. };
  29516. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29517. this.checkInputs = function () { };
  29518. for (var cam in this.attached) {
  29519. var input = this.attached[cam];
  29520. if (input.checkInputs) {
  29521. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29522. }
  29523. }
  29524. };
  29525. CameraInputsManager.prototype.clear = function () {
  29526. if (this.attachedElement) {
  29527. this.detachElement(this.attachedElement);
  29528. }
  29529. this.attached = {};
  29530. this.attachedElement = null;
  29531. this.checkInputs = function () { };
  29532. };
  29533. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29534. var inputs = {};
  29535. for (var cam in this.attached) {
  29536. var input = this.attached[cam];
  29537. var res = BABYLON.SerializationHelper.Serialize(input);
  29538. inputs[input.getTypeName()] = res;
  29539. }
  29540. serializedCamera.inputsmgr = inputs;
  29541. };
  29542. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29543. var parsedInputs = parsedCamera.inputsmgr;
  29544. if (parsedInputs) {
  29545. this.clear();
  29546. for (var n in parsedInputs) {
  29547. var construct = BABYLON.CameraInputTypes[n];
  29548. if (construct) {
  29549. var parsedinput = parsedInputs[n];
  29550. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29551. this.add(input);
  29552. }
  29553. }
  29554. }
  29555. else {
  29556. //2016-03-08 this part is for managing backward compatibility
  29557. for (var n in this.attached) {
  29558. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29559. if (construct) {
  29560. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29561. this.remove(this.attached[n]);
  29562. this.add(input);
  29563. }
  29564. }
  29565. }
  29566. };
  29567. return CameraInputsManager;
  29568. }());
  29569. BABYLON.CameraInputsManager = CameraInputsManager;
  29570. })(BABYLON || (BABYLON = {}));
  29571. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29572. /// <reference path="babylon.camera.ts" />
  29573. var BABYLON;
  29574. (function (BABYLON) {
  29575. var TargetCamera = (function (_super) {
  29576. __extends(TargetCamera, _super);
  29577. function TargetCamera(name, position, scene) {
  29578. var _this = _super.call(this, name, position, scene) || this;
  29579. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29580. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29581. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29582. _this.speed = 2.0;
  29583. _this.noRotationConstraint = false;
  29584. _this.lockedTarget = null;
  29585. _this._currentTarget = BABYLON.Vector3.Zero();
  29586. _this._viewMatrix = BABYLON.Matrix.Zero();
  29587. _this._camMatrix = BABYLON.Matrix.Zero();
  29588. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29589. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29590. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29591. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29592. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29593. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29594. _this._tempMatrix = BABYLON.Matrix.Zero();
  29595. return _this;
  29596. }
  29597. TargetCamera.prototype.getFrontPosition = function (distance) {
  29598. var direction = this.getTarget().subtract(this.position);
  29599. direction.normalize();
  29600. direction.scaleInPlace(distance);
  29601. return this.globalPosition.add(direction);
  29602. };
  29603. TargetCamera.prototype._getLockedTargetPosition = function () {
  29604. if (!this.lockedTarget) {
  29605. return null;
  29606. }
  29607. if (this.lockedTarget.absolutePosition) {
  29608. this.lockedTarget.computeWorldMatrix();
  29609. }
  29610. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29611. };
  29612. // Cache
  29613. TargetCamera.prototype._initCache = function () {
  29614. _super.prototype._initCache.call(this);
  29615. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29616. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29617. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29618. };
  29619. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29620. if (!ignoreParentClass) {
  29621. _super.prototype._updateCache.call(this);
  29622. }
  29623. var lockedTargetPosition = this._getLockedTargetPosition();
  29624. if (!lockedTargetPosition) {
  29625. this._cache.lockedTarget = null;
  29626. }
  29627. else {
  29628. if (!this._cache.lockedTarget) {
  29629. this._cache.lockedTarget = lockedTargetPosition.clone();
  29630. }
  29631. else {
  29632. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29633. }
  29634. }
  29635. this._cache.rotation.copyFrom(this.rotation);
  29636. if (this.rotationQuaternion)
  29637. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29638. };
  29639. // Synchronized
  29640. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29641. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29642. return false;
  29643. }
  29644. var lockedTargetPosition = this._getLockedTargetPosition();
  29645. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29646. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29647. };
  29648. // Methods
  29649. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29650. var engine = this.getEngine();
  29651. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29652. };
  29653. // Target
  29654. TargetCamera.prototype.setTarget = function (target) {
  29655. this.upVector.normalize();
  29656. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29657. this._camMatrix.invert();
  29658. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29659. var vDir = target.subtract(this.position);
  29660. if (vDir.x >= 0.0) {
  29661. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29662. }
  29663. else {
  29664. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29665. }
  29666. this.rotation.z = 0;
  29667. if (isNaN(this.rotation.x)) {
  29668. this.rotation.x = 0;
  29669. }
  29670. if (isNaN(this.rotation.y)) {
  29671. this.rotation.y = 0;
  29672. }
  29673. if (isNaN(this.rotation.z)) {
  29674. this.rotation.z = 0;
  29675. }
  29676. if (this.rotationQuaternion) {
  29677. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29678. }
  29679. };
  29680. /**
  29681. * Return the current target position of the camera. This value is expressed in local space.
  29682. */
  29683. TargetCamera.prototype.getTarget = function () {
  29684. return this._currentTarget;
  29685. };
  29686. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29687. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29688. };
  29689. TargetCamera.prototype._updatePosition = function () {
  29690. if (this.parent) {
  29691. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29692. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29693. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29694. return;
  29695. }
  29696. this.position.addInPlace(this.cameraDirection);
  29697. };
  29698. TargetCamera.prototype._checkInputs = function () {
  29699. var needToMove = this._decideIfNeedsToMove();
  29700. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29701. // Move
  29702. if (needToMove) {
  29703. this._updatePosition();
  29704. }
  29705. // Rotate
  29706. if (needToRotate) {
  29707. this.rotation.x += this.cameraRotation.x;
  29708. this.rotation.y += this.cameraRotation.y;
  29709. //rotate, if quaternion is set and rotation was used
  29710. if (this.rotationQuaternion) {
  29711. var len = this.rotation.lengthSquared();
  29712. if (len) {
  29713. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29714. }
  29715. }
  29716. if (!this.noRotationConstraint) {
  29717. var limit = (Math.PI / 2) * 0.95;
  29718. if (this.rotation.x > limit)
  29719. this.rotation.x = limit;
  29720. if (this.rotation.x < -limit)
  29721. this.rotation.x = -limit;
  29722. }
  29723. }
  29724. // Inertia
  29725. if (needToMove) {
  29726. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  29727. this.cameraDirection.x = 0;
  29728. }
  29729. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  29730. this.cameraDirection.y = 0;
  29731. }
  29732. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  29733. this.cameraDirection.z = 0;
  29734. }
  29735. this.cameraDirection.scaleInPlace(this.inertia);
  29736. }
  29737. if (needToRotate) {
  29738. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  29739. this.cameraRotation.x = 0;
  29740. }
  29741. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  29742. this.cameraRotation.y = 0;
  29743. }
  29744. this.cameraRotation.scaleInPlace(this.inertia);
  29745. }
  29746. _super.prototype._checkInputs.call(this);
  29747. };
  29748. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29749. if (this.rotationQuaternion) {
  29750. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29751. //update the up vector!
  29752. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29753. }
  29754. else {
  29755. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29756. }
  29757. };
  29758. TargetCamera.prototype._getViewMatrix = function () {
  29759. if (!this.lockedTarget) {
  29760. // Compute
  29761. this._updateCameraRotationMatrix();
  29762. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29763. // Computing target and final matrix
  29764. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29765. }
  29766. else {
  29767. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29768. }
  29769. if (this.getScene().useRightHandedSystem) {
  29770. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29771. }
  29772. else {
  29773. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29774. }
  29775. return this._viewMatrix;
  29776. };
  29777. /**
  29778. * @override
  29779. * Override Camera.createRigCamera
  29780. */
  29781. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29782. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29783. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29784. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29785. if (!this.rotationQuaternion) {
  29786. this.rotationQuaternion = new BABYLON.Quaternion();
  29787. }
  29788. rigCamera._cameraRigParams = {};
  29789. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29790. }
  29791. return rigCamera;
  29792. }
  29793. return null;
  29794. };
  29795. /**
  29796. * @override
  29797. * Override Camera._updateRigCameras
  29798. */
  29799. TargetCamera.prototype._updateRigCameras = function () {
  29800. var camLeft = this._rigCameras[0];
  29801. var camRight = this._rigCameras[1];
  29802. switch (this.cameraRigMode) {
  29803. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29804. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29805. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29806. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29807. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29808. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  29809. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  29810. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  29811. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  29812. camLeft.setTarget(this.getTarget());
  29813. camRight.setTarget(this.getTarget());
  29814. break;
  29815. case BABYLON.Camera.RIG_MODE_VR:
  29816. if (camLeft.rotationQuaternion) {
  29817. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29818. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29819. }
  29820. else {
  29821. camLeft.rotation.copyFrom(this.rotation);
  29822. camRight.rotation.copyFrom(this.rotation);
  29823. }
  29824. camLeft.position.copyFrom(this.position);
  29825. camRight.position.copyFrom(this.position);
  29826. break;
  29827. }
  29828. _super.prototype._updateRigCameras.call(this);
  29829. };
  29830. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  29831. if (!this._rigCamTransformMatrix) {
  29832. this._rigCamTransformMatrix = new BABYLON.Matrix();
  29833. }
  29834. var target = this.getTarget();
  29835. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  29836. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  29837. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  29838. };
  29839. TargetCamera.prototype.getClassName = function () {
  29840. return "TargetCamera";
  29841. };
  29842. return TargetCamera;
  29843. }(BABYLON.Camera));
  29844. __decorate([
  29845. BABYLON.serializeAsVector3()
  29846. ], TargetCamera.prototype, "rotation", void 0);
  29847. __decorate([
  29848. BABYLON.serialize()
  29849. ], TargetCamera.prototype, "speed", void 0);
  29850. __decorate([
  29851. BABYLON.serializeAsMeshReference("lockedTargetId")
  29852. ], TargetCamera.prototype, "lockedTarget", void 0);
  29853. BABYLON.TargetCamera = TargetCamera;
  29854. })(BABYLON || (BABYLON = {}));
  29855. //# sourceMappingURL=babylon.targetCamera.js.map
  29856. var BABYLON;
  29857. (function (BABYLON) {
  29858. var ArcRotateCameraKeyboardMoveInput = (function () {
  29859. function ArcRotateCameraKeyboardMoveInput() {
  29860. this._keys = [];
  29861. this.keysUp = [38];
  29862. this.keysDown = [40];
  29863. this.keysLeft = [37];
  29864. this.keysRight = [39];
  29865. }
  29866. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29867. var _this = this;
  29868. element.tabIndex = 1;
  29869. this._onKeyDown = function (evt) {
  29870. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29871. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29872. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29873. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29874. var index = _this._keys.indexOf(evt.keyCode);
  29875. if (index === -1) {
  29876. _this._keys.push(evt.keyCode);
  29877. }
  29878. if (evt.preventDefault) {
  29879. if (!noPreventDefault) {
  29880. evt.preventDefault();
  29881. }
  29882. }
  29883. }
  29884. };
  29885. this._onKeyUp = function (evt) {
  29886. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29887. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29888. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29889. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29890. var index = _this._keys.indexOf(evt.keyCode);
  29891. if (index >= 0) {
  29892. _this._keys.splice(index, 1);
  29893. }
  29894. if (evt.preventDefault) {
  29895. if (!noPreventDefault) {
  29896. evt.preventDefault();
  29897. }
  29898. }
  29899. }
  29900. };
  29901. this._onLostFocus = function () {
  29902. _this._keys = [];
  29903. };
  29904. element.addEventListener("keydown", this._onKeyDown, false);
  29905. element.addEventListener("keyup", this._onKeyUp, false);
  29906. BABYLON.Tools.RegisterTopRootEvents([
  29907. { name: "blur", handler: this._onLostFocus }
  29908. ]);
  29909. };
  29910. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  29911. if (element) {
  29912. element.removeEventListener("keydown", this._onKeyDown);
  29913. element.removeEventListener("keyup", this._onKeyUp);
  29914. }
  29915. BABYLON.Tools.UnregisterTopRootEvents([
  29916. { name: "blur", handler: this._onLostFocus }
  29917. ]);
  29918. this._keys = [];
  29919. this._onKeyDown = null;
  29920. this._onKeyUp = null;
  29921. this._onLostFocus = null;
  29922. };
  29923. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  29924. if (this._onKeyDown) {
  29925. var camera = this.camera;
  29926. for (var index = 0; index < this._keys.length; index++) {
  29927. var keyCode = this._keys[index];
  29928. if (this.keysLeft.indexOf(keyCode) !== -1) {
  29929. camera.inertialAlphaOffset -= 0.01;
  29930. }
  29931. else if (this.keysUp.indexOf(keyCode) !== -1) {
  29932. camera.inertialBetaOffset -= 0.01;
  29933. }
  29934. else if (this.keysRight.indexOf(keyCode) !== -1) {
  29935. camera.inertialAlphaOffset += 0.01;
  29936. }
  29937. else if (this.keysDown.indexOf(keyCode) !== -1) {
  29938. camera.inertialBetaOffset += 0.01;
  29939. }
  29940. }
  29941. }
  29942. };
  29943. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  29944. return "ArcRotateCameraKeyboardMoveInput";
  29945. };
  29946. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  29947. return "keyboard";
  29948. };
  29949. return ArcRotateCameraKeyboardMoveInput;
  29950. }());
  29951. __decorate([
  29952. BABYLON.serialize()
  29953. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  29954. __decorate([
  29955. BABYLON.serialize()
  29956. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  29957. __decorate([
  29958. BABYLON.serialize()
  29959. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  29960. __decorate([
  29961. BABYLON.serialize()
  29962. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  29963. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  29964. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  29965. })(BABYLON || (BABYLON = {}));
  29966. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  29967. var BABYLON;
  29968. (function (BABYLON) {
  29969. var ArcRotateCameraMouseWheelInput = (function () {
  29970. function ArcRotateCameraMouseWheelInput() {
  29971. this.wheelPrecision = 3.0;
  29972. }
  29973. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  29974. var _this = this;
  29975. this._wheel = function (p, s) {
  29976. //sanity check - this should be a PointerWheel event.
  29977. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  29978. return;
  29979. var event = p.event;
  29980. var delta = 0;
  29981. if (event.wheelDelta) {
  29982. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  29983. }
  29984. else if (event.detail) {
  29985. delta = -event.detail / _this.wheelPrecision;
  29986. }
  29987. if (delta)
  29988. _this.camera.inertialRadiusOffset += delta;
  29989. if (event.preventDefault) {
  29990. if (!noPreventDefault) {
  29991. event.preventDefault();
  29992. }
  29993. }
  29994. };
  29995. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  29996. };
  29997. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  29998. if (this._observer && element) {
  29999. this.camera.getScene().onPointerObservable.remove(this._observer);
  30000. this._observer = null;
  30001. this._wheel = null;
  30002. }
  30003. };
  30004. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30005. return "ArcRotateCameraMouseWheelInput";
  30006. };
  30007. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30008. return "mousewheel";
  30009. };
  30010. return ArcRotateCameraMouseWheelInput;
  30011. }());
  30012. __decorate([
  30013. BABYLON.serialize()
  30014. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30015. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30016. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30017. })(BABYLON || (BABYLON = {}));
  30018. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30019. var BABYLON;
  30020. (function (BABYLON) {
  30021. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30022. var ArcRotateCameraPointersInput = (function () {
  30023. function ArcRotateCameraPointersInput() {
  30024. this.buttons = [0, 1, 2];
  30025. this.angularSensibilityX = 1000.0;
  30026. this.angularSensibilityY = 1000.0;
  30027. this.pinchPrecision = 6.0;
  30028. this.panningSensibility = 50.0;
  30029. this._isPanClick = false;
  30030. this.pinchInwards = true;
  30031. }
  30032. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30033. var _this = this;
  30034. var engine = this.camera.getEngine();
  30035. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30036. var pointA, pointB;
  30037. var previousPinchDistance = 0;
  30038. this._pointerInput = function (p, s) {
  30039. var evt = p.event;
  30040. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30041. return;
  30042. }
  30043. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30044. try {
  30045. evt.srcElement.setPointerCapture(evt.pointerId);
  30046. }
  30047. catch (e) {
  30048. //Nothing to do with the error. Execution will continue.
  30049. }
  30050. // Manage panning with pan button click
  30051. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30052. // manage pointers
  30053. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30054. if (pointA === undefined) {
  30055. pointA = cacheSoloPointer;
  30056. }
  30057. else if (pointB === undefined) {
  30058. pointB = cacheSoloPointer;
  30059. }
  30060. if (!noPreventDefault) {
  30061. evt.preventDefault();
  30062. element.focus();
  30063. }
  30064. }
  30065. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30066. try {
  30067. evt.srcElement.releasePointerCapture(evt.pointerId);
  30068. }
  30069. catch (e) {
  30070. //Nothing to do with the error.
  30071. }
  30072. cacheSoloPointer = null;
  30073. previousPinchDistance = 0;
  30074. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30075. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30076. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30077. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30078. pointA = pointB = undefined;
  30079. if (!noPreventDefault) {
  30080. evt.preventDefault();
  30081. }
  30082. }
  30083. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30084. if (!noPreventDefault) {
  30085. evt.preventDefault();
  30086. }
  30087. // One button down
  30088. if (pointA && pointB === undefined) {
  30089. if (_this.panningSensibility !== 0 &&
  30090. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30091. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30092. _this.camera
  30093. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30094. _this.camera
  30095. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30096. }
  30097. else {
  30098. var offsetX = evt.clientX - cacheSoloPointer.x;
  30099. var offsetY = evt.clientY - cacheSoloPointer.y;
  30100. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30101. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30102. }
  30103. cacheSoloPointer.x = evt.clientX;
  30104. cacheSoloPointer.y = evt.clientY;
  30105. }
  30106. else if (pointA && pointB) {
  30107. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30108. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30109. ed.x = evt.clientX;
  30110. ed.y = evt.clientY;
  30111. var direction = _this.pinchInwards ? 1 : -1;
  30112. var distX = pointA.x - pointB.x;
  30113. var distY = pointA.y - pointB.y;
  30114. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30115. if (previousPinchDistance === 0) {
  30116. previousPinchDistance = pinchSquaredDistance;
  30117. return;
  30118. }
  30119. if (pinchSquaredDistance !== previousPinchDistance) {
  30120. _this.camera
  30121. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30122. (_this.pinchPrecision *
  30123. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30124. direction);
  30125. previousPinchDistance = pinchSquaredDistance;
  30126. }
  30127. }
  30128. }
  30129. };
  30130. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30131. this._onContextMenu = function (evt) {
  30132. evt.preventDefault();
  30133. };
  30134. if (!this.camera._useCtrlForPanning) {
  30135. element.addEventListener("contextmenu", this._onContextMenu, false);
  30136. }
  30137. this._onLostFocus = function () {
  30138. //this._keys = [];
  30139. pointA = pointB = undefined;
  30140. previousPinchDistance = 0;
  30141. cacheSoloPointer = null;
  30142. };
  30143. this._onMouseMove = function (evt) {
  30144. if (!engine.isPointerLock) {
  30145. return;
  30146. }
  30147. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30148. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30149. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30150. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30151. if (!noPreventDefault) {
  30152. evt.preventDefault();
  30153. }
  30154. };
  30155. this._onGestureStart = function (e) {
  30156. if (window.MSGesture === undefined) {
  30157. return;
  30158. }
  30159. if (!_this._MSGestureHandler) {
  30160. _this._MSGestureHandler = new MSGesture();
  30161. _this._MSGestureHandler.target = element;
  30162. }
  30163. _this._MSGestureHandler.addPointer(e.pointerId);
  30164. };
  30165. this._onGesture = function (e) {
  30166. _this.camera.radius *= e.scale;
  30167. if (e.preventDefault) {
  30168. if (!noPreventDefault) {
  30169. e.stopPropagation();
  30170. e.preventDefault();
  30171. }
  30172. }
  30173. };
  30174. element.addEventListener("mousemove", this._onMouseMove, false);
  30175. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30176. element.addEventListener("MSGestureChange", this._onGesture, false);
  30177. BABYLON.Tools.RegisterTopRootEvents([
  30178. { name: "blur", handler: this._onLostFocus }
  30179. ]);
  30180. };
  30181. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30182. if (element && this._observer) {
  30183. this.camera.getScene().onPointerObservable.remove(this._observer);
  30184. this._observer = null;
  30185. element.removeEventListener("contextmenu", this._onContextMenu);
  30186. element.removeEventListener("mousemove", this._onMouseMove);
  30187. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30188. element.removeEventListener("MSGestureChange", this._onGesture);
  30189. this._isPanClick = false;
  30190. this.pinchInwards = true;
  30191. this._onMouseMove = null;
  30192. this._onGestureStart = null;
  30193. this._onGesture = null;
  30194. this._MSGestureHandler = null;
  30195. this._onLostFocus = null;
  30196. this._onContextMenu = null;
  30197. }
  30198. BABYLON.Tools.UnregisterTopRootEvents([
  30199. { name: "blur", handler: this._onLostFocus }
  30200. ]);
  30201. };
  30202. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30203. return "ArcRotateCameraPointersInput";
  30204. };
  30205. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30206. return "pointers";
  30207. };
  30208. return ArcRotateCameraPointersInput;
  30209. }());
  30210. __decorate([
  30211. BABYLON.serialize()
  30212. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30213. __decorate([
  30214. BABYLON.serialize()
  30215. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30216. __decorate([
  30217. BABYLON.serialize()
  30218. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30219. __decorate([
  30220. BABYLON.serialize()
  30221. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30222. __decorate([
  30223. BABYLON.serialize()
  30224. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30225. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30226. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30227. })(BABYLON || (BABYLON = {}));
  30228. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30229. /// <reference path="babylon.targetCamera.ts" />
  30230. /// <reference path="..\Tools\babylon.tools.ts" />
  30231. var BABYLON;
  30232. (function (BABYLON) {
  30233. var ArcRotateCamera = (function (_super) {
  30234. __extends(ArcRotateCamera, _super);
  30235. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30236. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30237. _this.inertialAlphaOffset = 0;
  30238. _this.inertialBetaOffset = 0;
  30239. _this.inertialRadiusOffset = 0;
  30240. _this.lowerAlphaLimit = null;
  30241. _this.upperAlphaLimit = null;
  30242. _this.lowerBetaLimit = 0.01;
  30243. _this.upperBetaLimit = Math.PI;
  30244. _this.lowerRadiusLimit = null;
  30245. _this.upperRadiusLimit = null;
  30246. _this.inertialPanningX = 0;
  30247. _this.inertialPanningY = 0;
  30248. _this.panningInertia = 0.9;
  30249. //-- end properties for backward compatibility for inputs
  30250. _this.zoomOnFactor = 1;
  30251. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30252. _this.allowUpsideDown = true;
  30253. _this._viewMatrix = new BABYLON.Matrix();
  30254. // Panning
  30255. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30256. _this.checkCollisions = false;
  30257. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30258. _this._previousPosition = BABYLON.Vector3.Zero();
  30259. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30260. _this._newPosition = BABYLON.Vector3.Zero();
  30261. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30262. if (collidedMesh === void 0) { collidedMesh = null; }
  30263. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30264. newPosition.multiplyInPlace(_this._collider.radius);
  30265. }
  30266. if (!collidedMesh) {
  30267. _this._previousPosition.copyFrom(_this.position);
  30268. }
  30269. else {
  30270. _this.setPosition(newPosition);
  30271. if (_this.onCollide) {
  30272. _this.onCollide(collidedMesh);
  30273. }
  30274. }
  30275. // Recompute because of constraints
  30276. var cosa = Math.cos(_this.alpha);
  30277. var sina = Math.sin(_this.alpha);
  30278. var cosb = Math.cos(_this.beta);
  30279. var sinb = Math.sin(_this.beta);
  30280. if (sinb === 0) {
  30281. sinb = 0.0001;
  30282. }
  30283. var target = _this._getTargetPosition();
  30284. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30285. _this.position.copyFrom(_this._newPosition);
  30286. var up = _this.upVector;
  30287. if (_this.allowUpsideDown && _this.beta < 0) {
  30288. up = up.clone();
  30289. up = up.negate();
  30290. }
  30291. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30292. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30293. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30294. _this._collisionTriggered = false;
  30295. };
  30296. _this._target = BABYLON.Vector3.Zero();
  30297. if (target) {
  30298. _this.setTarget(target);
  30299. }
  30300. _this.alpha = alpha;
  30301. _this.beta = beta;
  30302. _this.radius = radius;
  30303. _this.getViewMatrix();
  30304. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30305. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30306. return _this;
  30307. }
  30308. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  30309. get: function () {
  30310. return this._target;
  30311. },
  30312. set: function (value) {
  30313. this.setTarget(value);
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30319. //-- begin properties for backward compatibility for inputs
  30320. get: function () {
  30321. var pointers = this.inputs.attached["pointers"];
  30322. if (pointers)
  30323. return pointers.angularSensibilityX;
  30324. },
  30325. set: function (value) {
  30326. var pointers = this.inputs.attached["pointers"];
  30327. if (pointers) {
  30328. pointers.angularSensibilityX = value;
  30329. }
  30330. },
  30331. enumerable: true,
  30332. configurable: true
  30333. });
  30334. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30335. get: function () {
  30336. var pointers = this.inputs.attached["pointers"];
  30337. if (pointers)
  30338. return pointers.angularSensibilityY;
  30339. },
  30340. set: function (value) {
  30341. var pointers = this.inputs.attached["pointers"];
  30342. if (pointers) {
  30343. pointers.angularSensibilityY = value;
  30344. }
  30345. },
  30346. enumerable: true,
  30347. configurable: true
  30348. });
  30349. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30350. get: function () {
  30351. var pointers = this.inputs.attached["pointers"];
  30352. if (pointers)
  30353. return pointers.pinchPrecision;
  30354. },
  30355. set: function (value) {
  30356. var pointers = this.inputs.attached["pointers"];
  30357. if (pointers) {
  30358. pointers.pinchPrecision = value;
  30359. }
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30365. get: function () {
  30366. var pointers = this.inputs.attached["pointers"];
  30367. if (pointers)
  30368. return pointers.panningSensibility;
  30369. },
  30370. set: function (value) {
  30371. var pointers = this.inputs.attached["pointers"];
  30372. if (pointers) {
  30373. pointers.panningSensibility = value;
  30374. }
  30375. },
  30376. enumerable: true,
  30377. configurable: true
  30378. });
  30379. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30380. get: function () {
  30381. var keyboard = this.inputs.attached["keyboard"];
  30382. if (keyboard)
  30383. return keyboard.keysUp;
  30384. },
  30385. set: function (value) {
  30386. var keyboard = this.inputs.attached["keyboard"];
  30387. if (keyboard)
  30388. keyboard.keysUp = value;
  30389. },
  30390. enumerable: true,
  30391. configurable: true
  30392. });
  30393. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30394. get: function () {
  30395. var keyboard = this.inputs.attached["keyboard"];
  30396. if (keyboard)
  30397. return keyboard.keysDown;
  30398. },
  30399. set: function (value) {
  30400. var keyboard = this.inputs.attached["keyboard"];
  30401. if (keyboard)
  30402. keyboard.keysDown = value;
  30403. },
  30404. enumerable: true,
  30405. configurable: true
  30406. });
  30407. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30408. get: function () {
  30409. var keyboard = this.inputs.attached["keyboard"];
  30410. if (keyboard)
  30411. return keyboard.keysLeft;
  30412. },
  30413. set: function (value) {
  30414. var keyboard = this.inputs.attached["keyboard"];
  30415. if (keyboard)
  30416. keyboard.keysLeft = value;
  30417. },
  30418. enumerable: true,
  30419. configurable: true
  30420. });
  30421. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30422. get: function () {
  30423. var keyboard = this.inputs.attached["keyboard"];
  30424. if (keyboard)
  30425. return keyboard.keysRight;
  30426. },
  30427. set: function (value) {
  30428. var keyboard = this.inputs.attached["keyboard"];
  30429. if (keyboard)
  30430. keyboard.keysRight = value;
  30431. },
  30432. enumerable: true,
  30433. configurable: true
  30434. });
  30435. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30436. get: function () {
  30437. var mousewheel = this.inputs.attached["mousewheel"];
  30438. if (mousewheel)
  30439. return mousewheel.wheelPrecision;
  30440. },
  30441. set: function (value) {
  30442. var mousewheel = this.inputs.attached["mousewheel"];
  30443. if (mousewheel)
  30444. mousewheel.wheelPrecision = value;
  30445. },
  30446. enumerable: true,
  30447. configurable: true
  30448. });
  30449. // Cache
  30450. ArcRotateCamera.prototype._initCache = function () {
  30451. _super.prototype._initCache.call(this);
  30452. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30453. this._cache.alpha = undefined;
  30454. this._cache.beta = undefined;
  30455. this._cache.radius = undefined;
  30456. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30457. };
  30458. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30459. if (!ignoreParentClass) {
  30460. _super.prototype._updateCache.call(this);
  30461. }
  30462. this._cache._target.copyFrom(this._getTargetPosition());
  30463. this._cache.alpha = this.alpha;
  30464. this._cache.beta = this.beta;
  30465. this._cache.radius = this.radius;
  30466. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30467. };
  30468. ArcRotateCamera.prototype._getTargetPosition = function () {
  30469. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  30470. var pos = this._targetHost.getAbsolutePosition();
  30471. if (this._targetBoundingCenter) {
  30472. pos.addToRef(this._targetBoundingCenter, this._target);
  30473. }
  30474. else {
  30475. this._target.copyFrom(pos);
  30476. }
  30477. }
  30478. var lockedTargetPosition = this._getLockedTargetPosition();
  30479. if (lockedTargetPosition) {
  30480. return lockedTargetPosition;
  30481. }
  30482. return this._target;
  30483. };
  30484. // Synchronized
  30485. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30486. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30487. return false;
  30488. return this._cache._target.equals(this._getTargetPosition())
  30489. && this._cache.alpha === this.alpha
  30490. && this._cache.beta === this.beta
  30491. && this._cache.radius === this.radius
  30492. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30493. };
  30494. // Methods
  30495. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30496. var _this = this;
  30497. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30498. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30499. this._useCtrlForPanning = useCtrlForPanning;
  30500. this._panningMouseButton = panningMouseButton;
  30501. this.inputs.attachElement(element, noPreventDefault);
  30502. this._reset = function () {
  30503. _this.inertialAlphaOffset = 0;
  30504. _this.inertialBetaOffset = 0;
  30505. _this.inertialRadiusOffset = 0;
  30506. };
  30507. };
  30508. ArcRotateCamera.prototype.detachControl = function (element) {
  30509. this.inputs.detachElement(element);
  30510. if (this._reset) {
  30511. this._reset();
  30512. }
  30513. };
  30514. ArcRotateCamera.prototype._checkInputs = function () {
  30515. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30516. if (this._collisionTriggered) {
  30517. return;
  30518. }
  30519. this.inputs.checkInputs();
  30520. // Inertia
  30521. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30522. if (this.getScene().useRightHandedSystem) {
  30523. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30524. }
  30525. else {
  30526. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30527. }
  30528. this.beta += this.inertialBetaOffset;
  30529. this.radius -= this.inertialRadiusOffset;
  30530. this.inertialAlphaOffset *= this.inertia;
  30531. this.inertialBetaOffset *= this.inertia;
  30532. this.inertialRadiusOffset *= this.inertia;
  30533. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  30534. this.inertialAlphaOffset = 0;
  30535. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  30536. this.inertialBetaOffset = 0;
  30537. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  30538. this.inertialRadiusOffset = 0;
  30539. }
  30540. // Panning inertia
  30541. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30542. if (!this._localDirection) {
  30543. this._localDirection = BABYLON.Vector3.Zero();
  30544. this._transformedDirection = BABYLON.Vector3.Zero();
  30545. }
  30546. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30547. this._localDirection.multiplyInPlace(this.panningAxis);
  30548. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30549. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30550. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30551. if (!this.panningAxis.y) {
  30552. this._transformedDirection.y = 0;
  30553. }
  30554. if (!this._targetHost) {
  30555. this._target.addInPlace(this._transformedDirection);
  30556. }
  30557. this.inertialPanningX *= this.panningInertia;
  30558. this.inertialPanningY *= this.panningInertia;
  30559. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  30560. this.inertialPanningX = 0;
  30561. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  30562. this.inertialPanningY = 0;
  30563. }
  30564. // Limits
  30565. this._checkLimits();
  30566. _super.prototype._checkInputs.call(this);
  30567. };
  30568. ArcRotateCamera.prototype._checkLimits = function () {
  30569. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30570. if (this.allowUpsideDown && this.beta > Math.PI) {
  30571. this.beta = this.beta - (2 * Math.PI);
  30572. }
  30573. }
  30574. else {
  30575. if (this.beta < this.lowerBetaLimit) {
  30576. this.beta = this.lowerBetaLimit;
  30577. }
  30578. }
  30579. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30580. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30581. this.beta = this.beta + (2 * Math.PI);
  30582. }
  30583. }
  30584. else {
  30585. if (this.beta > this.upperBetaLimit) {
  30586. this.beta = this.upperBetaLimit;
  30587. }
  30588. }
  30589. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30590. this.alpha = this.lowerAlphaLimit;
  30591. }
  30592. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30593. this.alpha = this.upperAlphaLimit;
  30594. }
  30595. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30596. this.radius = this.lowerRadiusLimit;
  30597. }
  30598. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30599. this.radius = this.upperRadiusLimit;
  30600. }
  30601. };
  30602. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30603. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30604. this.radius = radiusv3.length();
  30605. // Alpha
  30606. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30607. if (radiusv3.z < 0) {
  30608. this.alpha = 2 * Math.PI - this.alpha;
  30609. }
  30610. // Beta
  30611. this.beta = Math.acos(radiusv3.y / this.radius);
  30612. this._checkLimits();
  30613. };
  30614. ArcRotateCamera.prototype.setPosition = function (position) {
  30615. if (this.position.equals(position)) {
  30616. return;
  30617. }
  30618. this.position.copyFrom(position);
  30619. this.rebuildAnglesAndRadius();
  30620. };
  30621. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30622. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30623. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30624. if (target.getBoundingInfo) {
  30625. if (toBoundingCenter) {
  30626. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30627. }
  30628. else {
  30629. this._targetBoundingCenter = null;
  30630. }
  30631. this._targetHost = target;
  30632. this._target = this._getTargetPosition();
  30633. }
  30634. else {
  30635. var newTarget = target;
  30636. var currentTarget = this._getTargetPosition();
  30637. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  30638. return;
  30639. }
  30640. this._target = newTarget;
  30641. this._targetBoundingCenter = null;
  30642. }
  30643. this.rebuildAnglesAndRadius();
  30644. };
  30645. ArcRotateCamera.prototype._getViewMatrix = function () {
  30646. // Compute
  30647. var cosa = Math.cos(this.alpha);
  30648. var sina = Math.sin(this.alpha);
  30649. var cosb = Math.cos(this.beta);
  30650. var sinb = Math.sin(this.beta);
  30651. if (sinb === 0) {
  30652. sinb = 0.0001;
  30653. }
  30654. var target = this._getTargetPosition();
  30655. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30656. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30657. if (!this._collider) {
  30658. this._collider = new BABYLON.Collider();
  30659. }
  30660. this._collider.radius = this.collisionRadius;
  30661. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30662. this._collisionTriggered = true;
  30663. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30664. }
  30665. else {
  30666. this.position.copyFrom(this._newPosition);
  30667. var up = this.upVector;
  30668. if (this.allowUpsideDown && sinb < 0) {
  30669. up = up.clone();
  30670. up = up.negate();
  30671. }
  30672. if (this.getScene().useRightHandedSystem) {
  30673. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30674. }
  30675. else {
  30676. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30677. }
  30678. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30679. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30680. }
  30681. this._currentTarget = target;
  30682. return this._viewMatrix;
  30683. };
  30684. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30685. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30686. meshes = meshes || this.getScene().meshes;
  30687. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30688. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30689. this.radius = distance * this.zoomOnFactor;
  30690. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30691. };
  30692. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30693. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30694. var meshesOrMinMaxVector;
  30695. var distance;
  30696. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30697. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30698. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30699. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30700. }
  30701. else {
  30702. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30703. distance = meshesOrMinMaxVectorAndDistance.distance;
  30704. }
  30705. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30706. if (!doNotUpdateMaxZ) {
  30707. this.maxZ = distance * 2;
  30708. }
  30709. };
  30710. /**
  30711. * @override
  30712. * Override Camera.createRigCamera
  30713. */
  30714. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30715. var alphaShift;
  30716. switch (this.cameraRigMode) {
  30717. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30718. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30719. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30720. case BABYLON.Camera.RIG_MODE_VR:
  30721. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30722. break;
  30723. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30724. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30725. break;
  30726. }
  30727. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  30728. rigCam._cameraRigParams = {};
  30729. return rigCam;
  30730. };
  30731. /**
  30732. * @override
  30733. * Override Camera._updateRigCameras
  30734. */
  30735. ArcRotateCamera.prototype._updateRigCameras = function () {
  30736. var camLeft = this._rigCameras[0];
  30737. var camRight = this._rigCameras[1];
  30738. camLeft.beta = camRight.beta = this.beta;
  30739. camLeft.radius = camRight.radius = this.radius;
  30740. switch (this.cameraRigMode) {
  30741. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30743. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30744. case BABYLON.Camera.RIG_MODE_VR:
  30745. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30746. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30747. break;
  30748. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30749. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30750. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30751. break;
  30752. }
  30753. _super.prototype._updateRigCameras.call(this);
  30754. };
  30755. ArcRotateCamera.prototype.dispose = function () {
  30756. this.inputs.clear();
  30757. _super.prototype.dispose.call(this);
  30758. };
  30759. ArcRotateCamera.prototype.getClassName = function () {
  30760. return "ArcRotateCamera";
  30761. };
  30762. return ArcRotateCamera;
  30763. }(BABYLON.TargetCamera));
  30764. __decorate([
  30765. BABYLON.serialize()
  30766. ], ArcRotateCamera.prototype, "alpha", void 0);
  30767. __decorate([
  30768. BABYLON.serialize()
  30769. ], ArcRotateCamera.prototype, "beta", void 0);
  30770. __decorate([
  30771. BABYLON.serialize()
  30772. ], ArcRotateCamera.prototype, "radius", void 0);
  30773. __decorate([
  30774. BABYLON.serializeAsVector3("target")
  30775. ], ArcRotateCamera.prototype, "_target", void 0);
  30776. __decorate([
  30777. BABYLON.serialize()
  30778. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30779. __decorate([
  30780. BABYLON.serialize()
  30781. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30782. __decorate([
  30783. BABYLON.serialize()
  30784. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30785. __decorate([
  30786. BABYLON.serialize()
  30787. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30788. __decorate([
  30789. BABYLON.serialize()
  30790. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30791. __decorate([
  30792. BABYLON.serialize()
  30793. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30794. __decorate([
  30795. BABYLON.serialize()
  30796. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30797. __decorate([
  30798. BABYLON.serialize()
  30799. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30800. __decorate([
  30801. BABYLON.serialize()
  30802. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30803. __decorate([
  30804. BABYLON.serialize()
  30805. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30806. __decorate([
  30807. BABYLON.serialize()
  30808. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  30809. __decorate([
  30810. BABYLON.serialize()
  30811. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  30812. __decorate([
  30813. BABYLON.serialize()
  30814. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  30815. __decorate([
  30816. BABYLON.serialize()
  30817. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  30818. BABYLON.ArcRotateCamera = ArcRotateCamera;
  30819. })(BABYLON || (BABYLON = {}));
  30820. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  30821. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  30822. var BABYLON;
  30823. (function (BABYLON) {
  30824. var ArcRotateCameraInputsManager = (function (_super) {
  30825. __extends(ArcRotateCameraInputsManager, _super);
  30826. function ArcRotateCameraInputsManager(camera) {
  30827. return _super.call(this, camera) || this;
  30828. }
  30829. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  30830. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  30831. return this;
  30832. };
  30833. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  30834. this.add(new BABYLON.ArcRotateCameraPointersInput());
  30835. return this;
  30836. };
  30837. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  30838. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  30839. return this;
  30840. };
  30841. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  30842. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  30843. return this;
  30844. };
  30845. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  30846. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  30847. return this;
  30848. };
  30849. return ArcRotateCameraInputsManager;
  30850. }(BABYLON.CameraInputsManager));
  30851. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  30852. })(BABYLON || (BABYLON = {}));
  30853. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  30854. var BABYLON;
  30855. (function (BABYLON) {
  30856. var CubeTexture = (function (_super) {
  30857. __extends(CubeTexture, _super);
  30858. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  30859. if (onLoad === void 0) { onLoad = null; }
  30860. if (onError === void 0) { onError = null; }
  30861. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30862. var _this = _super.call(this, scene) || this;
  30863. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  30864. _this.name = rootUrl;
  30865. _this.url = rootUrl;
  30866. _this._noMipmap = noMipmap;
  30867. _this.hasAlpha = false;
  30868. _this._format = format;
  30869. if (!rootUrl && !files) {
  30870. return _this;
  30871. }
  30872. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  30873. if (!files) {
  30874. if (!extensions) {
  30875. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  30876. }
  30877. files = [];
  30878. for (var index = 0; index < extensions.length; index++) {
  30879. files.push(rootUrl + extensions[index]);
  30880. }
  30881. _this._extensions = extensions;
  30882. }
  30883. _this._files = files;
  30884. if (!_this._texture) {
  30885. if (!scene.useDelayedTextureLoading) {
  30886. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  30887. }
  30888. else {
  30889. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30890. }
  30891. }
  30892. else if (onLoad) {
  30893. if (_this._texture.isReady) {
  30894. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  30895. }
  30896. else {
  30897. _this._texture.onLoadedCallbacks.push(onLoad);
  30898. }
  30899. }
  30900. _this.isCube = true;
  30901. _this._textureMatrix = BABYLON.Matrix.Identity();
  30902. return _this;
  30903. }
  30904. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  30905. return new CubeTexture("", scene, null, noMipmap, files);
  30906. };
  30907. // Methods
  30908. CubeTexture.prototype.delayLoad = function () {
  30909. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30910. return;
  30911. }
  30912. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30913. this._texture = this._getFromCache(this.url, this._noMipmap);
  30914. if (!this._texture) {
  30915. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  30916. }
  30917. };
  30918. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  30919. return this._textureMatrix;
  30920. };
  30921. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  30922. var texture = BABYLON.SerializationHelper.Parse(function () {
  30923. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  30924. }, parsedTexture, scene);
  30925. // Animations
  30926. if (parsedTexture.animations) {
  30927. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30928. var parsedAnimation = parsedTexture.animations[animationIndex];
  30929. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30930. }
  30931. }
  30932. return texture;
  30933. };
  30934. CubeTexture.prototype.clone = function () {
  30935. var _this = this;
  30936. return BABYLON.SerializationHelper.Clone(function () {
  30937. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  30938. }, this);
  30939. };
  30940. return CubeTexture;
  30941. }(BABYLON.BaseTexture));
  30942. BABYLON.CubeTexture = CubeTexture;
  30943. })(BABYLON || (BABYLON = {}));
  30944. //# sourceMappingURL=babylon.cubeTexture.js.map
  30945. var BABYLON;
  30946. (function (BABYLON) {
  30947. var RenderTargetTexture = (function (_super) {
  30948. __extends(RenderTargetTexture, _super);
  30949. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  30950. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  30951. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30952. if (isCube === void 0) { isCube = false; }
  30953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30954. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  30955. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  30956. if (isMulti === void 0) { isMulti = false; }
  30957. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  30958. _this.isCube = isCube;
  30959. /**
  30960. * Use this list to define the list of mesh you want to render.
  30961. */
  30962. _this.renderList = new Array();
  30963. _this.renderParticles = true;
  30964. _this.renderSprites = false;
  30965. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  30966. // Events
  30967. /**
  30968. * An event triggered when the texture is unbind.
  30969. * @type {BABYLON.Observable}
  30970. */
  30971. _this.onAfterUnbindObservable = new BABYLON.Observable();
  30972. /**
  30973. * An event triggered before rendering the texture
  30974. * @type {BABYLON.Observable}
  30975. */
  30976. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30977. /**
  30978. * An event triggered after rendering the texture
  30979. * @type {BABYLON.Observable}
  30980. */
  30981. _this.onAfterRenderObservable = new BABYLON.Observable();
  30982. /**
  30983. * An event triggered after the texture clear
  30984. * @type {BABYLON.Observable}
  30985. */
  30986. _this.onClearObservable = new BABYLON.Observable();
  30987. _this._currentRefreshId = -1;
  30988. _this._refreshRate = 1;
  30989. _this._samples = 1;
  30990. scene = _this.getScene();
  30991. _this.name = name;
  30992. _this.isRenderTarget = true;
  30993. _this._size = size;
  30994. _this._generateMipMaps = generateMipMaps;
  30995. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  30996. // Rendering groups
  30997. _this._renderingManager = new BABYLON.RenderingManager(scene);
  30998. if (isMulti) {
  30999. return _this;
  31000. }
  31001. _this._renderTargetOptions = {
  31002. generateMipMaps: generateMipMaps,
  31003. type: type,
  31004. samplingMode: samplingMode,
  31005. generateDepthBuffer: generateDepthBuffer,
  31006. generateStencilBuffer: generateStencilBuffer
  31007. };
  31008. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31009. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31010. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31011. }
  31012. if (isCube) {
  31013. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  31014. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  31015. _this._textureMatrix = BABYLON.Matrix.Identity();
  31016. }
  31017. else {
  31018. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  31019. }
  31020. return _this;
  31021. }
  31022. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  31023. get: function () {
  31024. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  31025. },
  31026. enumerable: true,
  31027. configurable: true
  31028. });
  31029. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  31030. get: function () {
  31031. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  31037. get: function () {
  31038. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  31044. set: function (callback) {
  31045. if (this._onAfterUnbindObserver) {
  31046. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  31047. }
  31048. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  31054. set: function (callback) {
  31055. if (this._onBeforeRenderObserver) {
  31056. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31057. }
  31058. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31059. },
  31060. enumerable: true,
  31061. configurable: true
  31062. });
  31063. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  31064. set: function (callback) {
  31065. if (this._onAfterRenderObserver) {
  31066. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31067. }
  31068. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31069. },
  31070. enumerable: true,
  31071. configurable: true
  31072. });
  31073. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  31074. set: function (callback) {
  31075. if (this._onClearObserver) {
  31076. this.onClearObservable.remove(this._onClearObserver);
  31077. }
  31078. this._onClearObserver = this.onClearObservable.add(callback);
  31079. },
  31080. enumerable: true,
  31081. configurable: true
  31082. });
  31083. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  31084. get: function () {
  31085. return this._renderTargetOptions;
  31086. },
  31087. enumerable: true,
  31088. configurable: true
  31089. });
  31090. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  31091. get: function () {
  31092. return this._samples;
  31093. },
  31094. set: function (value) {
  31095. if (this._samples === value) {
  31096. return;
  31097. }
  31098. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  31099. },
  31100. enumerable: true,
  31101. configurable: true
  31102. });
  31103. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  31104. this._currentRefreshId = -1;
  31105. };
  31106. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  31107. get: function () {
  31108. return this._refreshRate;
  31109. },
  31110. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  31111. set: function (value) {
  31112. this._refreshRate = value;
  31113. this.resetRefreshCounter();
  31114. },
  31115. enumerable: true,
  31116. configurable: true
  31117. });
  31118. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  31119. if (!this._postProcessManager) {
  31120. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  31121. this._postProcesses = new Array();
  31122. }
  31123. this._postProcesses.push(postProcess);
  31124. this._postProcesses[0].autoClear = false;
  31125. };
  31126. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  31127. if (!this._postProcesses) {
  31128. return;
  31129. }
  31130. if (dispose) {
  31131. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  31132. var postProcess = _a[_i];
  31133. postProcess.dispose();
  31134. postProcess = null;
  31135. }
  31136. }
  31137. this._postProcesses = [];
  31138. };
  31139. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  31140. if (!this._postProcesses) {
  31141. return;
  31142. }
  31143. var index = this._postProcesses.indexOf(postProcess);
  31144. if (index === -1) {
  31145. return;
  31146. }
  31147. this._postProcesses.splice(index, 1);
  31148. if (this._postProcesses.length > 0) {
  31149. this._postProcesses[0].autoClear = false;
  31150. }
  31151. };
  31152. RenderTargetTexture.prototype._shouldRender = function () {
  31153. if (this._currentRefreshId === -1) {
  31154. this._currentRefreshId = 1;
  31155. return true;
  31156. }
  31157. if (this.refreshRate === this._currentRefreshId) {
  31158. this._currentRefreshId = 1;
  31159. return true;
  31160. }
  31161. this._currentRefreshId++;
  31162. return false;
  31163. };
  31164. RenderTargetTexture.prototype.isReady = function () {
  31165. if (!this.getScene().renderTargetsEnabled) {
  31166. return false;
  31167. }
  31168. return _super.prototype.isReady.call(this);
  31169. };
  31170. RenderTargetTexture.prototype.getRenderSize = function () {
  31171. return this._size;
  31172. };
  31173. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  31174. get: function () {
  31175. return true;
  31176. },
  31177. enumerable: true,
  31178. configurable: true
  31179. });
  31180. RenderTargetTexture.prototype.scale = function (ratio) {
  31181. var newSize = this._size * ratio;
  31182. this.resize(newSize);
  31183. };
  31184. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  31185. if (this.isCube) {
  31186. return this._textureMatrix;
  31187. }
  31188. return _super.prototype.getReflectionTextureMatrix.call(this);
  31189. };
  31190. RenderTargetTexture.prototype.resize = function (size) {
  31191. this.releaseInternalTexture();
  31192. if (this.isCube) {
  31193. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  31194. }
  31195. else {
  31196. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  31197. }
  31198. };
  31199. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  31200. var scene = this.getScene();
  31201. var engine = scene.getEngine();
  31202. if (this.useCameraPostProcesses !== undefined) {
  31203. useCameraPostProcess = this.useCameraPostProcesses;
  31204. }
  31205. if (this._waitingRenderList) {
  31206. this.renderList = [];
  31207. for (var index = 0; index < this._waitingRenderList.length; index++) {
  31208. var id = this._waitingRenderList[index];
  31209. this.renderList.push(scene.getMeshByID(id));
  31210. }
  31211. delete this._waitingRenderList;
  31212. }
  31213. // Is predicate defined?
  31214. if (this.renderListPredicate) {
  31215. this.renderList.splice(0); // Clear previous renderList
  31216. var sceneMeshes = this.getScene().meshes;
  31217. for (var index = 0; index < sceneMeshes.length; index++) {
  31218. var mesh = sceneMeshes[index];
  31219. if (this.renderListPredicate(mesh)) {
  31220. this.renderList.push(mesh);
  31221. }
  31222. }
  31223. }
  31224. if (this.renderList && this.renderList.length === 0) {
  31225. return;
  31226. }
  31227. // Set custom projection.
  31228. // Needs to be before binding to prevent changing the aspect ratio.
  31229. var camera;
  31230. if (this.activeCamera) {
  31231. camera = this.activeCamera;
  31232. engine.setViewport(this.activeCamera.viewport);
  31233. if (this.activeCamera !== scene.activeCamera) {
  31234. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  31235. }
  31236. }
  31237. else {
  31238. camera = scene.activeCamera;
  31239. engine.setViewport(scene.activeCamera.viewport);
  31240. }
  31241. // Prepare renderingManager
  31242. this._renderingManager.reset();
  31243. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  31244. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  31245. var sceneRenderId = scene.getRenderId();
  31246. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  31247. var mesh = currentRenderList[meshIndex];
  31248. if (mesh) {
  31249. if (!mesh.isReady()) {
  31250. // Reset _currentRefreshId
  31251. this.resetRefreshCounter();
  31252. continue;
  31253. }
  31254. mesh._preActivateForIntermediateRendering(sceneRenderId);
  31255. var isMasked = void 0;
  31256. if (!this.renderList) {
  31257. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  31258. }
  31259. else {
  31260. isMasked = false;
  31261. }
  31262. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  31263. mesh._activate(sceneRenderId);
  31264. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31265. var subMesh = mesh.subMeshes[subIndex];
  31266. scene._activeIndices.addCount(subMesh.indexCount, false);
  31267. this._renderingManager.dispatch(subMesh);
  31268. }
  31269. }
  31270. }
  31271. }
  31272. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  31273. var particleSystem = scene.particleSystems[particleIndex];
  31274. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  31275. continue;
  31276. }
  31277. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  31278. this._renderingManager.dispatchParticles(particleSystem);
  31279. }
  31280. }
  31281. if (this.isCube) {
  31282. for (var face = 0; face < 6; face++) {
  31283. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31284. scene.incrementRenderId();
  31285. scene.resetCachedMaterial();
  31286. }
  31287. }
  31288. else {
  31289. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31290. }
  31291. this.onAfterUnbindObservable.notifyObservers(this);
  31292. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  31293. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  31294. }
  31295. engine.setViewport(scene.activeCamera.viewport);
  31296. scene.resetCachedMaterial();
  31297. };
  31298. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  31299. var _this = this;
  31300. var scene = this.getScene();
  31301. var engine = scene.getEngine();
  31302. // Bind
  31303. if (this._postProcessManager) {
  31304. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  31305. }
  31306. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  31307. if (this.isCube) {
  31308. engine.bindFramebuffer(this._texture, faceIndex);
  31309. }
  31310. else {
  31311. engine.bindFramebuffer(this._texture);
  31312. }
  31313. }
  31314. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  31315. // Clear
  31316. if (this.onClearObservable.hasObservers()) {
  31317. this.onClearObservable.notifyObservers(engine);
  31318. }
  31319. else {
  31320. engine.clear(scene.clearColor, true, true, true);
  31321. }
  31322. if (!this._doNotChangeAspectRatio) {
  31323. scene.updateTransformMatrix(true);
  31324. }
  31325. // Render
  31326. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  31327. if (this._postProcessManager) {
  31328. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  31329. }
  31330. else if (useCameraPostProcess) {
  31331. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  31332. }
  31333. if (!this._doNotChangeAspectRatio) {
  31334. scene.updateTransformMatrix(true);
  31335. }
  31336. // Dump ?
  31337. if (dumpForDebug) {
  31338. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  31339. }
  31340. // Unbind
  31341. if (!this.isCube || faceIndex === 5) {
  31342. if (this.isCube) {
  31343. if (faceIndex === 5) {
  31344. engine.generateMipMapsForCubemap(this._texture);
  31345. }
  31346. }
  31347. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  31348. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  31349. });
  31350. }
  31351. else {
  31352. this.onAfterRenderObservable.notifyObservers(faceIndex);
  31353. }
  31354. };
  31355. /**
  31356. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  31357. * This allowed control for front to back rendering or reversly depending of the special needs.
  31358. *
  31359. * @param renderingGroupId The rendering group id corresponding to its index
  31360. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  31361. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  31362. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  31363. */
  31364. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  31365. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  31366. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  31367. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  31368. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  31369. };
  31370. /**
  31371. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  31372. *
  31373. * @param renderingGroupId The rendering group id corresponding to its index
  31374. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  31375. */
  31376. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  31377. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  31378. };
  31379. RenderTargetTexture.prototype.clone = function () {
  31380. var textureSize = this.getSize();
  31381. 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);
  31382. // Base texture
  31383. newTexture.hasAlpha = this.hasAlpha;
  31384. newTexture.level = this.level;
  31385. // RenderTarget Texture
  31386. newTexture.coordinatesMode = this.coordinatesMode;
  31387. newTexture.renderList = this.renderList.slice(0);
  31388. return newTexture;
  31389. };
  31390. RenderTargetTexture.prototype.serialize = function () {
  31391. if (!this.name) {
  31392. return null;
  31393. }
  31394. var serializationObject = _super.prototype.serialize.call(this);
  31395. serializationObject.renderTargetSize = this.getRenderSize();
  31396. serializationObject.renderList = [];
  31397. for (var index = 0; index < this.renderList.length; index++) {
  31398. serializationObject.renderList.push(this.renderList[index].id);
  31399. }
  31400. return serializationObject;
  31401. };
  31402. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  31403. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  31404. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  31405. };
  31406. RenderTargetTexture.prototype.dispose = function () {
  31407. if (this._postProcessManager) {
  31408. this._postProcessManager.dispose();
  31409. this._postProcessManager = null;
  31410. }
  31411. this.clearPostProcesses(true);
  31412. // Remove from custom render targets
  31413. var scene = this.getScene();
  31414. var index = scene.customRenderTargets.indexOf(this);
  31415. if (index >= 0) {
  31416. scene.customRenderTargets.splice(index, 1);
  31417. }
  31418. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  31419. var camera = _a[_i];
  31420. index = camera.customRenderTargets.indexOf(this);
  31421. if (index >= 0) {
  31422. camera.customRenderTargets.splice(index, 1);
  31423. }
  31424. }
  31425. _super.prototype.dispose.call(this);
  31426. };
  31427. return RenderTargetTexture;
  31428. }(BABYLON.Texture));
  31429. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  31430. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  31431. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  31432. BABYLON.RenderTargetTexture = RenderTargetTexture;
  31433. })(BABYLON || (BABYLON = {}));
  31434. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  31435. var BABYLON;
  31436. (function (BABYLON) {
  31437. ;
  31438. var MultiRenderTarget = (function (_super) {
  31439. __extends(MultiRenderTarget, _super);
  31440. function MultiRenderTarget(name, size, count, scene, options) {
  31441. var _this = this;
  31442. options = options || {};
  31443. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  31444. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  31445. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  31446. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  31447. if (!_this.isSupported) {
  31448. _this.dispose();
  31449. return;
  31450. }
  31451. var types = [];
  31452. var samplingModes = [];
  31453. for (var i = 0; i < count; i++) {
  31454. if (options.types && options.types[i]) {
  31455. types.push(options.types[i]);
  31456. }
  31457. else {
  31458. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  31459. }
  31460. if (options.samplingModes && options.samplingModes[i]) {
  31461. samplingModes.push(options.samplingModes[i]);
  31462. }
  31463. else {
  31464. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31465. }
  31466. }
  31467. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  31468. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  31469. _this._count = count;
  31470. _this._size = size;
  31471. _this._multiRenderTargetOptions = {
  31472. samplingModes: samplingModes,
  31473. generateMipMaps: generateMipMaps,
  31474. generateDepthBuffer: generateDepthBuffer,
  31475. generateStencilBuffer: generateStencilBuffer,
  31476. generateDepthTexture: generateDepthTexture,
  31477. types: types,
  31478. textureCount: count
  31479. };
  31480. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  31481. _this._createInternalTextures();
  31482. return _this;
  31483. }
  31484. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  31485. get: function () {
  31486. var engine = this.getScene().getEngine();
  31487. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  31493. get: function () {
  31494. return this._textures;
  31495. },
  31496. enumerable: true,
  31497. configurable: true
  31498. });
  31499. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  31500. get: function () {
  31501. return this._textures[this._textures.length - 1];
  31502. },
  31503. enumerable: true,
  31504. configurable: true
  31505. });
  31506. MultiRenderTarget.prototype._createInternalTextures = function () {
  31507. this._textures = [];
  31508. for (var i = 0; i < this._webGLTextures.length; i++) {
  31509. var texture = new BABYLON.Texture(null, this.getScene());
  31510. texture._texture = this._webGLTextures[i];
  31511. this._textures.push(texture);
  31512. }
  31513. // Keeps references to frame buffer and stencil/depth buffer
  31514. this._texture = this._webGLTextures[0];
  31515. };
  31516. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  31517. get: function () {
  31518. return this._samples;
  31519. },
  31520. set: function (value) {
  31521. if (this._samples === value) {
  31522. return;
  31523. }
  31524. for (var i = 0; i < this._webGLTextures.length; i++) {
  31525. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  31526. }
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. MultiRenderTarget.prototype.resize = function (size) {
  31532. this.releaseInternalTextures();
  31533. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  31534. this._createInternalTextures();
  31535. };
  31536. MultiRenderTarget.prototype.dispose = function () {
  31537. this.releaseInternalTextures();
  31538. _super.prototype.dispose.call(this);
  31539. };
  31540. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  31541. if (!this._webGLTextures) {
  31542. return;
  31543. }
  31544. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  31545. if (this._webGLTextures[i] !== undefined) {
  31546. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  31547. this._webGLTextures.splice(i, 1);
  31548. }
  31549. }
  31550. };
  31551. return MultiRenderTarget;
  31552. }(BABYLON.RenderTargetTexture));
  31553. BABYLON.MultiRenderTarget = MultiRenderTarget;
  31554. })(BABYLON || (BABYLON = {}));
  31555. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  31556. /// <reference path="babylon.renderTargetTexture.ts" />
  31557. var BABYLON;
  31558. (function (BABYLON) {
  31559. var MirrorTexture = (function (_super) {
  31560. __extends(MirrorTexture, _super);
  31561. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  31562. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31564. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31565. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  31566. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  31567. _this._transformMatrix = BABYLON.Matrix.Zero();
  31568. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  31569. _this._blurKernelX = 0;
  31570. _this._blurKernelY = 0;
  31571. _this._blurRatio = 1.0;
  31572. _this.onBeforeRenderObservable.add(function () {
  31573. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  31574. _this._savedViewMatrix = scene.getViewMatrix();
  31575. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  31576. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  31577. scene.clipPlane = _this.mirrorPlane;
  31578. scene.getEngine().cullBackFaces = false;
  31579. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  31580. });
  31581. _this.onAfterRenderObservable.add(function () {
  31582. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  31583. scene.getEngine().cullBackFaces = true;
  31584. scene._mirroredCameraPosition = null;
  31585. delete scene.clipPlane;
  31586. });
  31587. return _this;
  31588. }
  31589. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  31590. get: function () {
  31591. return this._blurRatio;
  31592. },
  31593. set: function (value) {
  31594. if (this._blurRatio === value) {
  31595. return;
  31596. }
  31597. this._blurRatio = value;
  31598. this._preparePostProcesses();
  31599. },
  31600. enumerable: true,
  31601. configurable: true
  31602. });
  31603. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  31604. set: function (value) {
  31605. this.blurKernelX = value;
  31606. this.blurKernelY = value;
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  31612. get: function () {
  31613. return this._blurKernelX;
  31614. },
  31615. set: function (value) {
  31616. if (this._blurKernelX === value) {
  31617. return;
  31618. }
  31619. this._blurKernelX = value;
  31620. this._preparePostProcesses();
  31621. },
  31622. enumerable: true,
  31623. configurable: true
  31624. });
  31625. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  31626. get: function () {
  31627. return this._blurKernelY;
  31628. },
  31629. set: function (value) {
  31630. if (this._blurKernelY === value) {
  31631. return;
  31632. }
  31633. this._blurKernelY = value;
  31634. this._preparePostProcesses();
  31635. },
  31636. enumerable: true,
  31637. configurable: true
  31638. });
  31639. MirrorTexture.prototype._preparePostProcesses = function () {
  31640. this.clearPostProcesses(true);
  31641. if (this._blurKernelX && this._blurKernelY) {
  31642. var engine = this.getScene().getEngine();
  31643. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  31644. 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);
  31645. this._blurX.autoClear = false;
  31646. if (this._blurRatio === 1 && this.samples < 2) {
  31647. this._blurX.outputTexture = this._texture;
  31648. }
  31649. else {
  31650. this._blurX.alwaysForcePOT = true;
  31651. }
  31652. 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);
  31653. this._blurY.autoClear = false;
  31654. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  31655. this.addPostProcess(this._blurX);
  31656. this.addPostProcess(this._blurY);
  31657. }
  31658. };
  31659. MirrorTexture.prototype.clone = function () {
  31660. var textureSize = this.getSize();
  31661. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  31662. // Base texture
  31663. newTexture.hasAlpha = this.hasAlpha;
  31664. newTexture.level = this.level;
  31665. // Mirror Texture
  31666. newTexture.mirrorPlane = this.mirrorPlane.clone();
  31667. newTexture.renderList = this.renderList.slice(0);
  31668. return newTexture;
  31669. };
  31670. MirrorTexture.prototype.serialize = function () {
  31671. if (!this.name) {
  31672. return null;
  31673. }
  31674. var serializationObject = _super.prototype.serialize.call(this);
  31675. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  31676. return serializationObject;
  31677. };
  31678. return MirrorTexture;
  31679. }(BABYLON.RenderTargetTexture));
  31680. BABYLON.MirrorTexture = MirrorTexture;
  31681. })(BABYLON || (BABYLON = {}));
  31682. //# sourceMappingURL=babylon.mirrorTexture.js.map
  31683. /// <reference path="babylon.renderTargetTexture.ts" />
  31684. var BABYLON;
  31685. (function (BABYLON) {
  31686. /**
  31687. * Creates a refraction texture used by refraction channel of the standard material.
  31688. * @param name the texture name
  31689. * @param size size of the underlying texture
  31690. * @param scene root scene
  31691. */
  31692. var RefractionTexture = (function (_super) {
  31693. __extends(RefractionTexture, _super);
  31694. function RefractionTexture(name, size, scene, generateMipMaps) {
  31695. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  31696. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  31697. _this.depth = 2.0;
  31698. _this.onBeforeRenderObservable.add(function () {
  31699. scene.clipPlane = _this.refractionPlane;
  31700. });
  31701. _this.onAfterRenderObservable.add(function () {
  31702. delete scene.clipPlane;
  31703. });
  31704. return _this;
  31705. }
  31706. RefractionTexture.prototype.clone = function () {
  31707. var textureSize = this.getSize();
  31708. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  31709. // Base texture
  31710. newTexture.hasAlpha = this.hasAlpha;
  31711. newTexture.level = this.level;
  31712. // Refraction Texture
  31713. newTexture.refractionPlane = this.refractionPlane.clone();
  31714. newTexture.renderList = this.renderList.slice(0);
  31715. newTexture.depth = this.depth;
  31716. return newTexture;
  31717. };
  31718. RefractionTexture.prototype.serialize = function () {
  31719. if (!this.name) {
  31720. return null;
  31721. }
  31722. var serializationObject = _super.prototype.serialize.call(this);
  31723. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  31724. serializationObject.depth = this.depth;
  31725. return serializationObject;
  31726. };
  31727. return RefractionTexture;
  31728. }(BABYLON.RenderTargetTexture));
  31729. BABYLON.RefractionTexture = RefractionTexture;
  31730. })(BABYLON || (BABYLON = {}));
  31731. //# sourceMappingURL=babylon.refractionTexture.js.map
  31732. /// <reference path="babylon.texture.ts" />
  31733. var BABYLON;
  31734. (function (BABYLON) {
  31735. var DynamicTexture = (function (_super) {
  31736. __extends(DynamicTexture, _super);
  31737. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  31738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31739. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31740. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  31741. _this.name = name;
  31742. var engine = _this.getScene().getEngine();
  31743. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31744. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31745. _this._generateMipMaps = generateMipMaps;
  31746. if (options.getContext) {
  31747. _this._canvas = options;
  31748. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31749. }
  31750. else {
  31751. _this._canvas = document.createElement("canvas");
  31752. if (options.width) {
  31753. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31754. }
  31755. else {
  31756. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  31757. }
  31758. }
  31759. var textureSize = _this.getSize();
  31760. _this._canvas.width = textureSize.width;
  31761. _this._canvas.height = textureSize.height;
  31762. _this._context = _this._canvas.getContext("2d");
  31763. return _this;
  31764. }
  31765. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  31766. get: function () {
  31767. return true;
  31768. },
  31769. enumerable: true,
  31770. configurable: true
  31771. });
  31772. DynamicTexture.prototype._recreate = function (textureSize) {
  31773. this._canvas.width = textureSize.width;
  31774. this._canvas.height = textureSize.height;
  31775. this.releaseInternalTexture();
  31776. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  31777. };
  31778. DynamicTexture.prototype.scale = function (ratio) {
  31779. var textureSize = this.getSize();
  31780. textureSize.width *= ratio;
  31781. textureSize.height *= ratio;
  31782. this._recreate(textureSize);
  31783. };
  31784. DynamicTexture.prototype.scaleTo = function (width, height) {
  31785. var textureSize = this.getSize();
  31786. textureSize.width = width;
  31787. textureSize.height = height;
  31788. this._recreate(textureSize);
  31789. };
  31790. DynamicTexture.prototype.getContext = function () {
  31791. return this._context;
  31792. };
  31793. DynamicTexture.prototype.clear = function () {
  31794. var size = this.getSize();
  31795. this._context.fillRect(0, 0, size.width, size.height);
  31796. };
  31797. DynamicTexture.prototype.update = function (invertY) {
  31798. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  31799. };
  31800. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  31801. if (update === void 0) { update = true; }
  31802. var size = this.getSize();
  31803. if (clearColor) {
  31804. this._context.fillStyle = clearColor;
  31805. this._context.fillRect(0, 0, size.width, size.height);
  31806. }
  31807. this._context.font = font;
  31808. if (x === null || x === undefined) {
  31809. var textSize = this._context.measureText(text);
  31810. x = (size.width - textSize.width) / 2;
  31811. }
  31812. if (y === null || y === undefined) {
  31813. var fontSize = parseInt((font.replace(/\D/g, '')));
  31814. ;
  31815. y = (size.height / 2) + (fontSize / 3.65);
  31816. }
  31817. this._context.fillStyle = color;
  31818. this._context.fillText(text, x, y);
  31819. if (update) {
  31820. this.update(invertY);
  31821. }
  31822. };
  31823. DynamicTexture.prototype.clone = function () {
  31824. var textureSize = this.getSize();
  31825. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  31826. // Base texture
  31827. newTexture.hasAlpha = this.hasAlpha;
  31828. newTexture.level = this.level;
  31829. // Dynamic Texture
  31830. newTexture.wrapU = this.wrapU;
  31831. newTexture.wrapV = this.wrapV;
  31832. return newTexture;
  31833. };
  31834. return DynamicTexture;
  31835. }(BABYLON.Texture));
  31836. BABYLON.DynamicTexture = DynamicTexture;
  31837. })(BABYLON || (BABYLON = {}));
  31838. //# sourceMappingURL=babylon.dynamicTexture.js.map
  31839. var BABYLON;
  31840. (function (BABYLON) {
  31841. var VideoTexture = (function (_super) {
  31842. __extends(VideoTexture, _super);
  31843. /**
  31844. * Creates a video texture.
  31845. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  31846. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  31847. * @param {BABYLON.Scene} scene is obviously the current scene.
  31848. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  31849. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  31850. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  31851. */
  31852. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  31853. if (generateMipMaps === void 0) { generateMipMaps = false; }
  31854. if (invertY === void 0) { invertY = false; }
  31855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31856. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  31857. _this._autoLaunch = true;
  31858. var urls;
  31859. _this.name = name;
  31860. if (urlsOrVideo instanceof HTMLVideoElement) {
  31861. _this.video = urlsOrVideo;
  31862. }
  31863. else {
  31864. urls = urlsOrVideo;
  31865. _this.video = document.createElement("video");
  31866. _this.video.autoplay = false;
  31867. _this.video.loop = true;
  31868. }
  31869. _this._generateMipMaps = generateMipMaps;
  31870. _this._samplingMode = samplingMode;
  31871. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  31872. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31873. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31874. }
  31875. else {
  31876. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31877. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31878. _this._generateMipMaps = false;
  31879. }
  31880. if (urls) {
  31881. _this.video.addEventListener("canplay", function () {
  31882. _this._createTexture();
  31883. });
  31884. urls.forEach(function (url) {
  31885. var source = document.createElement("source");
  31886. source.src = url;
  31887. _this.video.appendChild(source);
  31888. });
  31889. }
  31890. else {
  31891. _this._createTexture();
  31892. }
  31893. _this._lastUpdate = BABYLON.Tools.Now;
  31894. return _this;
  31895. }
  31896. VideoTexture.prototype.__setTextureReady = function () {
  31897. this._texture.isReady = true;
  31898. };
  31899. VideoTexture.prototype._createTexture = function () {
  31900. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  31901. if (this._autoLaunch) {
  31902. this._autoLaunch = false;
  31903. this.video.play();
  31904. }
  31905. this._setTextureReady = this.__setTextureReady.bind(this);
  31906. this.video.addEventListener("playing", this._setTextureReady);
  31907. };
  31908. VideoTexture.prototype.update = function () {
  31909. var now = BABYLON.Tools.Now;
  31910. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  31911. return false;
  31912. }
  31913. this._lastUpdate = now;
  31914. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  31915. return true;
  31916. };
  31917. VideoTexture.prototype.dispose = function () {
  31918. _super.prototype.dispose.call(this);
  31919. this.video.removeEventListener("playing", this._setTextureReady);
  31920. };
  31921. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  31922. var video = document.createElement("video");
  31923. var constraintsDeviceId;
  31924. if (constraints && constraints.deviceId) {
  31925. constraintsDeviceId = {
  31926. exact: constraints.deviceId
  31927. };
  31928. }
  31929. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  31930. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  31931. if (navigator.getUserMedia) {
  31932. navigator.getUserMedia({
  31933. video: {
  31934. deviceId: constraintsDeviceId,
  31935. width: {
  31936. min: (constraints && constraints.minWidth) || 256,
  31937. max: (constraints && constraints.maxWidth) || 640
  31938. },
  31939. height: {
  31940. min: (constraints && constraints.minHeight) || 256,
  31941. max: (constraints && constraints.maxHeight) || 480
  31942. }
  31943. }
  31944. }, function (stream) {
  31945. if (video.mozSrcObject !== undefined) {
  31946. video.mozSrcObject = stream;
  31947. }
  31948. else {
  31949. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  31950. }
  31951. video.play();
  31952. if (onReady) {
  31953. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  31954. }
  31955. }, function (e) {
  31956. BABYLON.Tools.Error(e.name);
  31957. });
  31958. }
  31959. };
  31960. return VideoTexture;
  31961. }(BABYLON.Texture));
  31962. BABYLON.VideoTexture = VideoTexture;
  31963. })(BABYLON || (BABYLON = {}));
  31964. //# sourceMappingURL=babylon.videoTexture.js.map
  31965. var BABYLON;
  31966. (function (BABYLON) {
  31967. var RawTexture = (function (_super) {
  31968. __extends(RawTexture, _super);
  31969. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31970. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31971. if (invertY === void 0) { invertY = false; }
  31972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31973. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  31974. _this.format = format;
  31975. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31976. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31977. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31978. return _this;
  31979. }
  31980. RawTexture.prototype.update = function (data) {
  31981. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31982. };
  31983. // Statics
  31984. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31986. if (invertY === void 0) { invertY = false; }
  31987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31988. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31989. };
  31990. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31991. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31992. if (invertY === void 0) { invertY = false; }
  31993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31994. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31995. };
  31996. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31997. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31998. if (invertY === void 0) { invertY = false; }
  31999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32000. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32001. };
  32002. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32003. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32004. if (invertY === void 0) { invertY = false; }
  32005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32006. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32007. };
  32008. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32009. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32010. if (invertY === void 0) { invertY = false; }
  32011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32012. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32013. };
  32014. return RawTexture;
  32015. }(BABYLON.Texture));
  32016. BABYLON.RawTexture = RawTexture;
  32017. })(BABYLON || (BABYLON = {}));
  32018. //# sourceMappingURL=babylon.rawTexture.js.map
  32019. var BABYLON;
  32020. (function (BABYLON) {
  32021. var Internals;
  32022. (function (Internals) {
  32023. /*
  32024. * Based on jsTGALoader - Javascript loader for TGA file
  32025. * By Vincent Thibault
  32026. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  32027. */
  32028. var TGATools = (function () {
  32029. function TGATools() {
  32030. }
  32031. TGATools.GetTGAHeader = function (data) {
  32032. var offset = 0;
  32033. var header = {
  32034. id_length: data[offset++],
  32035. colormap_type: data[offset++],
  32036. image_type: data[offset++],
  32037. colormap_index: data[offset++] | data[offset++] << 8,
  32038. colormap_length: data[offset++] | data[offset++] << 8,
  32039. colormap_size: data[offset++],
  32040. origin: [
  32041. data[offset++] | data[offset++] << 8,
  32042. data[offset++] | data[offset++] << 8
  32043. ],
  32044. width: data[offset++] | data[offset++] << 8,
  32045. height: data[offset++] | data[offset++] << 8,
  32046. pixel_size: data[offset++],
  32047. flags: data[offset++]
  32048. };
  32049. return header;
  32050. };
  32051. TGATools.UploadContent = function (gl, data) {
  32052. // Not enough data to contain header ?
  32053. if (data.length < 19) {
  32054. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  32055. return;
  32056. }
  32057. // Read Header
  32058. var offset = 18;
  32059. var header = TGATools.GetTGAHeader(data);
  32060. // Assume it's a valid Targa file.
  32061. if (header.id_length + offset > data.length) {
  32062. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  32063. return;
  32064. }
  32065. // Skip not needed data
  32066. offset += header.id_length;
  32067. var use_rle = false;
  32068. var use_pal = false;
  32069. var use_rgb = false;
  32070. var use_grey = false;
  32071. // Get some informations.
  32072. switch (header.image_type) {
  32073. case TGATools._TYPE_RLE_INDEXED:
  32074. use_rle = true;
  32075. case TGATools._TYPE_INDEXED:
  32076. use_pal = true;
  32077. break;
  32078. case TGATools._TYPE_RLE_RGB:
  32079. use_rle = true;
  32080. case TGATools._TYPE_RGB:
  32081. use_rgb = true;
  32082. break;
  32083. case TGATools._TYPE_RLE_GREY:
  32084. use_rle = true;
  32085. case TGATools._TYPE_GREY:
  32086. use_grey = true;
  32087. break;
  32088. }
  32089. var pixel_data;
  32090. var numAlphaBits = header.flags & 0xf;
  32091. var pixel_size = header.pixel_size >> 3;
  32092. var pixel_total = header.width * header.height * pixel_size;
  32093. // Read palettes
  32094. var palettes;
  32095. if (use_pal) {
  32096. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  32097. }
  32098. // Read LRE
  32099. if (use_rle) {
  32100. pixel_data = new Uint8Array(pixel_total);
  32101. var c, count, i;
  32102. var localOffset = 0;
  32103. var pixels = new Uint8Array(pixel_size);
  32104. while (offset < pixel_total && localOffset < pixel_total) {
  32105. c = data[offset++];
  32106. count = (c & 0x7f) + 1;
  32107. // RLE pixels
  32108. if (c & 0x80) {
  32109. // Bind pixel tmp array
  32110. for (i = 0; i < pixel_size; ++i) {
  32111. pixels[i] = data[offset++];
  32112. }
  32113. // Copy pixel array
  32114. for (i = 0; i < count; ++i) {
  32115. pixel_data.set(pixels, localOffset + i * pixel_size);
  32116. }
  32117. localOffset += pixel_size * count;
  32118. }
  32119. else {
  32120. count *= pixel_size;
  32121. for (i = 0; i < count; ++i) {
  32122. pixel_data[localOffset + i] = data[offset++];
  32123. }
  32124. localOffset += count;
  32125. }
  32126. }
  32127. }
  32128. else {
  32129. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  32130. }
  32131. // Load to texture
  32132. var x_start, y_start, x_step, y_step, y_end, x_end;
  32133. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  32134. default:
  32135. case TGATools._ORIGIN_UL:
  32136. x_start = 0;
  32137. x_step = 1;
  32138. x_end = header.width;
  32139. y_start = 0;
  32140. y_step = 1;
  32141. y_end = header.height;
  32142. break;
  32143. case TGATools._ORIGIN_BL:
  32144. x_start = 0;
  32145. x_step = 1;
  32146. x_end = header.width;
  32147. y_start = header.height - 1;
  32148. y_step = -1;
  32149. y_end = -1;
  32150. break;
  32151. case TGATools._ORIGIN_UR:
  32152. x_start = header.width - 1;
  32153. x_step = -1;
  32154. x_end = -1;
  32155. y_start = 0;
  32156. y_step = 1;
  32157. y_end = header.height;
  32158. break;
  32159. case TGATools._ORIGIN_BR:
  32160. x_start = header.width - 1;
  32161. x_step = -1;
  32162. x_end = -1;
  32163. y_start = header.height - 1;
  32164. y_step = -1;
  32165. y_end = -1;
  32166. break;
  32167. }
  32168. // Load the specify method
  32169. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  32170. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  32171. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  32172. };
  32173. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32174. var image = pixel_data, colormap = palettes;
  32175. var width = header.width, height = header.height;
  32176. var color, i = 0, x, y;
  32177. var imageData = new Uint8Array(width * height * 4);
  32178. for (y = y_start; y !== y_end; y += y_step) {
  32179. for (x = x_start; x !== x_end; x += x_step, i++) {
  32180. color = image[i];
  32181. imageData[(x + width * y) * 4 + 3] = 255;
  32182. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  32183. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  32184. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  32185. }
  32186. }
  32187. return imageData;
  32188. };
  32189. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32190. var image = pixel_data;
  32191. var width = header.width, height = header.height;
  32192. var color, i = 0, x, y;
  32193. var imageData = new Uint8Array(width * height * 4);
  32194. for (y = y_start; y !== y_end; y += y_step) {
  32195. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32196. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  32197. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  32198. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  32199. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  32200. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  32201. }
  32202. }
  32203. return imageData;
  32204. };
  32205. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32206. var image = pixel_data;
  32207. var width = header.width, height = header.height;
  32208. var i = 0, x, y;
  32209. var imageData = new Uint8Array(width * height * 4);
  32210. for (y = y_start; y !== y_end; y += y_step) {
  32211. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  32212. imageData[(x + width * y) * 4 + 3] = 255;
  32213. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32214. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32215. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32216. }
  32217. }
  32218. return imageData;
  32219. };
  32220. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32221. var image = pixel_data;
  32222. var width = header.width, height = header.height;
  32223. var i = 0, x, y;
  32224. var imageData = new Uint8Array(width * height * 4);
  32225. for (y = y_start; y !== y_end; y += y_step) {
  32226. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  32227. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32228. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32229. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32230. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  32231. }
  32232. }
  32233. return imageData;
  32234. };
  32235. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32236. var image = pixel_data;
  32237. var width = header.width, height = header.height;
  32238. var color, i = 0, x, y;
  32239. var imageData = new Uint8Array(width * height * 4);
  32240. for (y = y_start; y !== y_end; y += y_step) {
  32241. for (x = x_start; x !== x_end; x += x_step, i++) {
  32242. color = image[i];
  32243. imageData[(x + width * y) * 4 + 0] = color;
  32244. imageData[(x + width * y) * 4 + 1] = color;
  32245. imageData[(x + width * y) * 4 + 2] = color;
  32246. imageData[(x + width * y) * 4 + 3] = 255;
  32247. }
  32248. }
  32249. return imageData;
  32250. };
  32251. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32252. var image = pixel_data;
  32253. var width = header.width, height = header.height;
  32254. var i = 0, x, y;
  32255. var imageData = new Uint8Array(width * height * 4);
  32256. for (y = y_start; y !== y_end; y += y_step) {
  32257. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32258. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  32259. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  32260. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32261. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  32262. }
  32263. }
  32264. return imageData;
  32265. };
  32266. return TGATools;
  32267. }());
  32268. TGATools._TYPE_NO_DATA = 0;
  32269. TGATools._TYPE_INDEXED = 1;
  32270. TGATools._TYPE_RGB = 2;
  32271. TGATools._TYPE_GREY = 3;
  32272. TGATools._TYPE_RLE_INDEXED = 9;
  32273. TGATools._TYPE_RLE_RGB = 10;
  32274. TGATools._TYPE_RLE_GREY = 11;
  32275. TGATools._ORIGIN_MASK = 0x30;
  32276. TGATools._ORIGIN_SHIFT = 0x04;
  32277. TGATools._ORIGIN_BL = 0x00;
  32278. TGATools._ORIGIN_BR = 0x01;
  32279. TGATools._ORIGIN_UL = 0x02;
  32280. TGATools._ORIGIN_UR = 0x03;
  32281. Internals.TGATools = TGATools;
  32282. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32283. })(BABYLON || (BABYLON = {}));
  32284. //# sourceMappingURL=babylon.tga.js.map
  32285. var BABYLON;
  32286. (function (BABYLON) {
  32287. var Internals;
  32288. (function (Internals) {
  32289. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32290. // All values and structures referenced from:
  32291. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32292. var DDS_MAGIC = 0x20534444;
  32293. 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;
  32294. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32295. 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;
  32296. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32297. function FourCCToInt32(value) {
  32298. return value.charCodeAt(0) +
  32299. (value.charCodeAt(1) << 8) +
  32300. (value.charCodeAt(2) << 16) +
  32301. (value.charCodeAt(3) << 24);
  32302. }
  32303. function Int32ToFourCC(value) {
  32304. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32305. }
  32306. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32307. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32308. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32309. var headerLengthInt = 31; // The header length in 32 bit ints
  32310. // Offsets into the header array
  32311. var off_magic = 0;
  32312. var off_size = 1;
  32313. var off_flags = 2;
  32314. var off_height = 3;
  32315. var off_width = 4;
  32316. var off_mipmapCount = 7;
  32317. var off_pfFlags = 20;
  32318. var off_pfFourCC = 21;
  32319. var off_RGBbpp = 22;
  32320. var off_RMask = 23;
  32321. var off_GMask = 24;
  32322. var off_BMask = 25;
  32323. var off_AMask = 26;
  32324. var off_caps1 = 27;
  32325. var off_caps2 = 28;
  32326. ;
  32327. var DDSTools = (function () {
  32328. function DDSTools() {
  32329. }
  32330. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32331. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32332. var mipmapCount = 1;
  32333. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32334. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32335. }
  32336. return {
  32337. width: header[off_width],
  32338. height: header[off_height],
  32339. mipmapCount: mipmapCount,
  32340. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32341. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32342. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32343. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32344. };
  32345. };
  32346. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32347. var byteArray = new Uint8Array(dataLength);
  32348. var srcData = new Uint8Array(arrayBuffer);
  32349. var index = 0;
  32350. for (var y = height - 1; y >= 0; y--) {
  32351. for (var x = 0; x < width; x++) {
  32352. var srcPos = dataOffset + (x + y * width) * 4;
  32353. byteArray[index + 2] = srcData[srcPos];
  32354. byteArray[index + 1] = srcData[srcPos + 1];
  32355. byteArray[index] = srcData[srcPos + 2];
  32356. byteArray[index + 3] = srcData[srcPos + 3];
  32357. index += 4;
  32358. }
  32359. }
  32360. return byteArray;
  32361. };
  32362. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32363. var byteArray = new Uint8Array(dataLength);
  32364. var srcData = new Uint8Array(arrayBuffer);
  32365. var index = 0;
  32366. for (var y = height - 1; y >= 0; y--) {
  32367. for (var x = 0; x < width; x++) {
  32368. var srcPos = dataOffset + (x + y * width) * 3;
  32369. byteArray[index + 2] = srcData[srcPos];
  32370. byteArray[index + 1] = srcData[srcPos + 1];
  32371. byteArray[index] = srcData[srcPos + 2];
  32372. index += 3;
  32373. }
  32374. }
  32375. return byteArray;
  32376. };
  32377. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32378. var byteArray = new Uint8Array(dataLength);
  32379. var srcData = new Uint8Array(arrayBuffer);
  32380. var index = 0;
  32381. for (var y = height - 1; y >= 0; y--) {
  32382. for (var x = 0; x < width; x++) {
  32383. var srcPos = dataOffset + (x + y * width);
  32384. byteArray[index] = srcData[srcPos];
  32385. index++;
  32386. }
  32387. }
  32388. return byteArray;
  32389. };
  32390. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32391. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32392. if (header[off_magic] != DDS_MAGIC) {
  32393. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32394. return;
  32395. }
  32396. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32397. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32398. return;
  32399. }
  32400. if (info.isFourCC) {
  32401. fourCC = header[off_pfFourCC];
  32402. switch (fourCC) {
  32403. case FOURCC_DXT1:
  32404. blockBytes = 8;
  32405. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32406. break;
  32407. case FOURCC_DXT3:
  32408. blockBytes = 16;
  32409. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32410. break;
  32411. case FOURCC_DXT5:
  32412. blockBytes = 16;
  32413. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32414. break;
  32415. default:
  32416. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32417. return;
  32418. }
  32419. }
  32420. mipmapCount = 1;
  32421. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32422. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32423. }
  32424. var bpp = header[off_RGBbpp];
  32425. for (var face = 0; face < faces; face++) {
  32426. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32427. width = header[off_width];
  32428. height = header[off_height];
  32429. dataOffset = header[off_size] + 4;
  32430. for (i = 0; i < mipmapCount; ++i) {
  32431. if (info.isRGB) {
  32432. if (bpp === 24) {
  32433. dataLength = width * height * 3;
  32434. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32435. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  32436. }
  32437. else {
  32438. dataLength = width * height * 4;
  32439. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32440. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  32441. }
  32442. }
  32443. else if (info.isLuminance) {
  32444. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  32445. var unpaddedRowSize = width;
  32446. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  32447. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  32448. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32449. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  32450. }
  32451. else {
  32452. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  32453. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  32454. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  32455. }
  32456. dataOffset += dataLength;
  32457. width *= 0.5;
  32458. height *= 0.5;
  32459. width = Math.max(1.0, width);
  32460. height = Math.max(1.0, height);
  32461. }
  32462. }
  32463. };
  32464. return DDSTools;
  32465. }());
  32466. Internals.DDSTools = DDSTools;
  32467. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32468. })(BABYLON || (BABYLON = {}));
  32469. //# sourceMappingURL=babylon.dds.js.map
  32470. var BABYLON;
  32471. (function (BABYLON) {
  32472. var Internals;
  32473. (function (Internals) {
  32474. /**
  32475. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  32476. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  32477. */
  32478. var KhronosTextureContainer = (function () {
  32479. /**
  32480. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  32481. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  32482. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  32483. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  32484. */
  32485. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  32486. this.arrayBuffer = arrayBuffer;
  32487. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  32488. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  32489. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  32490. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  32491. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  32492. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  32493. BABYLON.Tools.Error("texture missing KTX identifier");
  32494. return;
  32495. }
  32496. // load the reset of the header in native 32 bit int
  32497. var header = new Int32Array(this.arrayBuffer, 12, 13);
  32498. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  32499. var oppositeEndianess = header[0] === 0x01020304;
  32500. // read all the header elements in order they exist in the file, without modification (sans endainness)
  32501. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  32502. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  32503. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  32504. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  32505. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  32506. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  32507. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  32508. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  32509. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  32510. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  32511. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  32512. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  32513. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  32514. if (this.glType !== 0) {
  32515. BABYLON.Tools.Error("only compressed formats currently supported");
  32516. return;
  32517. }
  32518. else {
  32519. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  32520. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  32521. }
  32522. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  32523. BABYLON.Tools.Error("only 2D textures currently supported");
  32524. return;
  32525. }
  32526. if (this.numberOfArrayElements !== 0) {
  32527. BABYLON.Tools.Error("texture arrays not currently supported");
  32528. return;
  32529. }
  32530. if (this.numberOfFaces !== facesExpected) {
  32531. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  32532. return;
  32533. }
  32534. // we now have a completely validated file, so could use existence of loadType as success
  32535. // would need to make this more elaborate & adjust checks above to support more than one load type
  32536. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  32537. }
  32538. // not as fast hardware based, but will probably never need to use
  32539. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  32540. return ((val & 0xFF) << 24)
  32541. | ((val & 0xFF00) << 8)
  32542. | ((val >> 8) & 0xFF00)
  32543. | ((val >> 24) & 0xFF);
  32544. };
  32545. /**
  32546. * It is assumed that the texture has already been created & is currently bound
  32547. */
  32548. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  32549. switch (this.loadType) {
  32550. case KhronosTextureContainer.COMPRESSED_2D:
  32551. this._upload2DCompressedLevels(gl, loadMipmaps);
  32552. break;
  32553. case KhronosTextureContainer.TEX_2D:
  32554. case KhronosTextureContainer.COMPRESSED_3D:
  32555. case KhronosTextureContainer.TEX_3D:
  32556. }
  32557. };
  32558. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  32559. // initialize width & height for level 1
  32560. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  32561. var width = this.pixelWidth;
  32562. var height = this.pixelHeight;
  32563. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  32564. for (var level = 0; level < mipmapCount; level++) {
  32565. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  32566. for (var face = 0; face < this.numberOfFaces; face++) {
  32567. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32568. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  32569. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  32570. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  32571. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  32572. }
  32573. width = Math.max(1.0, width * 0.5);
  32574. height = Math.max(1.0, height * 0.5);
  32575. }
  32576. };
  32577. return KhronosTextureContainer;
  32578. }());
  32579. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  32580. // load types
  32581. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  32582. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  32583. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  32584. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  32585. Internals.KhronosTextureContainer = KhronosTextureContainer;
  32586. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32587. })(BABYLON || (BABYLON = {}));
  32588. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  32589. var BABYLON;
  32590. (function (BABYLON) {
  32591. var PostProcess = (function () {
  32592. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  32593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32594. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32595. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  32596. if (blockCompilation === void 0) { blockCompilation = false; }
  32597. this.name = name;
  32598. this.width = -1;
  32599. this.height = -1;
  32600. this.autoClear = true;
  32601. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  32602. /*
  32603. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32604. Can only be used on a single postprocess or on the last one of a chain.
  32605. */
  32606. this.enablePixelPerfectMode = false;
  32607. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  32608. this.alwaysForcePOT = false;
  32609. this.samples = 1;
  32610. this._reusable = false;
  32611. this._textures = new BABYLON.SmartArray(2);
  32612. this._currentRenderTextureInd = 0;
  32613. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32614. this._texelSize = BABYLON.Vector2.Zero();
  32615. // Events
  32616. /**
  32617. * An event triggered when the postprocess is activated.
  32618. * @type {BABYLON.Observable}
  32619. */
  32620. this.onActivateObservable = new BABYLON.Observable();
  32621. /**
  32622. * An event triggered when the postprocess changes its size.
  32623. * @type {BABYLON.Observable}
  32624. */
  32625. this.onSizeChangedObservable = new BABYLON.Observable();
  32626. /**
  32627. * An event triggered when the postprocess applies its effect.
  32628. * @type {BABYLON.Observable}
  32629. */
  32630. this.onApplyObservable = new BABYLON.Observable();
  32631. /**
  32632. * An event triggered before rendering the postprocess
  32633. * @type {BABYLON.Observable}
  32634. */
  32635. this.onBeforeRenderObservable = new BABYLON.Observable();
  32636. /**
  32637. * An event triggered after rendering the postprocess
  32638. * @type {BABYLON.Observable}
  32639. */
  32640. this.onAfterRenderObservable = new BABYLON.Observable();
  32641. if (camera != null) {
  32642. this._camera = camera;
  32643. this._scene = camera.getScene();
  32644. camera.attachPostProcess(this);
  32645. this._engine = this._scene.getEngine();
  32646. }
  32647. else {
  32648. this._engine = engine;
  32649. }
  32650. this._options = options;
  32651. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32652. this._reusable = reusable || false;
  32653. this._textureType = textureType;
  32654. this._samplers = samplers || [];
  32655. this._samplers.push("textureSampler");
  32656. this._fragmentUrl = fragmentUrl;
  32657. this._vertexUrl = vertexUrl;
  32658. this._parameters = parameters || [];
  32659. this._parameters.push("scale");
  32660. this._indexParameters = indexParameters;
  32661. if (!blockCompilation) {
  32662. this.updateEffect(defines);
  32663. }
  32664. }
  32665. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32666. set: function (callback) {
  32667. if (this._onActivateObserver) {
  32668. this.onActivateObservable.remove(this._onActivateObserver);
  32669. }
  32670. this._onActivateObserver = this.onActivateObservable.add(callback);
  32671. },
  32672. enumerable: true,
  32673. configurable: true
  32674. });
  32675. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32676. set: function (callback) {
  32677. if (this._onSizeChangedObserver) {
  32678. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32679. }
  32680. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32681. },
  32682. enumerable: true,
  32683. configurable: true
  32684. });
  32685. Object.defineProperty(PostProcess.prototype, "onApply", {
  32686. set: function (callback) {
  32687. if (this._onApplyObserver) {
  32688. this.onApplyObservable.remove(this._onApplyObserver);
  32689. }
  32690. this._onApplyObserver = this.onApplyObservable.add(callback);
  32691. },
  32692. enumerable: true,
  32693. configurable: true
  32694. });
  32695. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32696. set: function (callback) {
  32697. if (this._onBeforeRenderObserver) {
  32698. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32699. }
  32700. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32701. },
  32702. enumerable: true,
  32703. configurable: true
  32704. });
  32705. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32706. set: function (callback) {
  32707. if (this._onAfterRenderObserver) {
  32708. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32709. }
  32710. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32711. },
  32712. enumerable: true,
  32713. configurable: true
  32714. });
  32715. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  32716. get: function () {
  32717. return this._textures.data[this._currentRenderTextureInd];
  32718. },
  32719. set: function (value) {
  32720. this._forcedOutputTexture = value;
  32721. },
  32722. enumerable: true,
  32723. configurable: true
  32724. });
  32725. PostProcess.prototype.getCamera = function () {
  32726. return this._camera;
  32727. };
  32728. Object.defineProperty(PostProcess.prototype, "texelSize", {
  32729. get: function () {
  32730. if (this._shareOutputWithPostProcess) {
  32731. return this._shareOutputWithPostProcess.texelSize;
  32732. }
  32733. if (this._forcedOutputTexture) {
  32734. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  32735. }
  32736. return this._texelSize;
  32737. },
  32738. enumerable: true,
  32739. configurable: true
  32740. });
  32741. PostProcess.prototype.getEngine = function () {
  32742. return this._engine;
  32743. };
  32744. PostProcess.prototype.getEffect = function () {
  32745. return this._effect;
  32746. };
  32747. PostProcess.prototype.shareOutputWith = function (postProcess) {
  32748. this._disposeTextures();
  32749. this._shareOutputWithPostProcess = postProcess;
  32750. return this;
  32751. };
  32752. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  32753. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  32754. };
  32755. PostProcess.prototype.isReusable = function () {
  32756. return this._reusable;
  32757. };
  32758. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32759. PostProcess.prototype.markTextureDirty = function () {
  32760. this.width = -1;
  32761. };
  32762. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  32763. var _this = this;
  32764. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  32765. camera = camera || this._camera;
  32766. var scene = camera.getScene();
  32767. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32768. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32769. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32770. var desiredWidth = this._options.width || requiredWidth;
  32771. var desiredHeight = this._options.height || requiredHeight;
  32772. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  32773. if (!this._options.width) {
  32774. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  32775. }
  32776. if (!this._options.height) {
  32777. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  32778. }
  32779. }
  32780. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32781. if (this._textures.length > 0) {
  32782. for (var i = 0; i < this._textures.length; i++) {
  32783. this._engine._releaseTexture(this._textures.data[i]);
  32784. }
  32785. this._textures.reset();
  32786. }
  32787. this.width = desiredWidth;
  32788. this.height = desiredHeight;
  32789. var textureSize = { width: this.width, height: this.height };
  32790. var textureOptions = {
  32791. generateMipMaps: false,
  32792. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  32793. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  32794. samplingMode: this.renderTargetSamplingMode,
  32795. type: this._textureType
  32796. };
  32797. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32798. if (this._reusable) {
  32799. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32800. }
  32801. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  32802. this.onSizeChangedObservable.notifyObservers(this);
  32803. }
  32804. this._textures.forEach(function (texture) {
  32805. if (texture.samples !== _this.samples) {
  32806. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  32807. }
  32808. });
  32809. }
  32810. var target;
  32811. if (this._shareOutputWithPostProcess) {
  32812. target = this._shareOutputWithPostProcess.outputTexture;
  32813. }
  32814. else if (this._forcedOutputTexture) {
  32815. target = this._forcedOutputTexture;
  32816. this.width = this._forcedOutputTexture._width;
  32817. this.height = this._forcedOutputTexture._height;
  32818. }
  32819. else {
  32820. target = this.outputTexture;
  32821. }
  32822. if (this.enablePixelPerfectMode) {
  32823. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32824. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  32825. }
  32826. else {
  32827. this._scaleRatio.copyFromFloats(1, 1);
  32828. this._engine.bindFramebuffer(target);
  32829. }
  32830. this.onActivateObservable.notifyObservers(camera);
  32831. // Clear
  32832. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  32833. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  32834. }
  32835. if (this._reusable) {
  32836. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32837. }
  32838. };
  32839. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32840. get: function () {
  32841. return this._effect.isSupported;
  32842. },
  32843. enumerable: true,
  32844. configurable: true
  32845. });
  32846. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  32847. get: function () {
  32848. if (this._shareOutputWithPostProcess) {
  32849. return this._shareOutputWithPostProcess.aspectRatio;
  32850. }
  32851. if (this._forcedOutputTexture) {
  32852. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  32853. }
  32854. return this.width / this.height;
  32855. },
  32856. enumerable: true,
  32857. configurable: true
  32858. });
  32859. PostProcess.prototype.apply = function () {
  32860. // Check
  32861. if (!this._effect || !this._effect.isReady())
  32862. return null;
  32863. // States
  32864. this._engine.enableEffect(this._effect);
  32865. this._engine.setState(false);
  32866. this._engine.setDepthBuffer(false);
  32867. this._engine.setDepthWrite(false);
  32868. // Alpha
  32869. this._engine.setAlphaMode(this.alphaMode);
  32870. if (this.alphaConstants) {
  32871. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  32872. }
  32873. // Texture
  32874. var source;
  32875. if (this._shareOutputWithPostProcess) {
  32876. source = this._shareOutputWithPostProcess.outputTexture;
  32877. }
  32878. else if (this._forcedOutputTexture) {
  32879. source = this._forcedOutputTexture;
  32880. }
  32881. else {
  32882. source = this.outputTexture;
  32883. }
  32884. this._effect._bindTexture("textureSampler", source);
  32885. // Parameters
  32886. this._effect.setVector2("scale", this._scaleRatio);
  32887. this.onApplyObservable.notifyObservers(this._effect);
  32888. return this._effect;
  32889. };
  32890. PostProcess.prototype._disposeTextures = function () {
  32891. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  32892. return;
  32893. }
  32894. if (this._textures.length > 0) {
  32895. for (var i = 0; i < this._textures.length; i++) {
  32896. this._engine._releaseTexture(this._textures.data[i]);
  32897. }
  32898. }
  32899. this._textures.dispose();
  32900. };
  32901. PostProcess.prototype.dispose = function (camera) {
  32902. camera = camera || this._camera;
  32903. this._disposeTextures();
  32904. if (!camera) {
  32905. return;
  32906. }
  32907. camera.detachPostProcess(this);
  32908. var index = camera._postProcesses.indexOf(this);
  32909. if (index === 0 && camera._postProcesses.length > 0) {
  32910. this._camera._postProcesses[0].markTextureDirty();
  32911. }
  32912. this.onActivateObservable.clear();
  32913. this.onAfterRenderObservable.clear();
  32914. this.onApplyObservable.clear();
  32915. this.onBeforeRenderObservable.clear();
  32916. this.onSizeChangedObservable.clear();
  32917. };
  32918. return PostProcess;
  32919. }());
  32920. BABYLON.PostProcess = PostProcess;
  32921. })(BABYLON || (BABYLON = {}));
  32922. //# sourceMappingURL=babylon.postProcess.js.map
  32923. var BABYLON;
  32924. (function (BABYLON) {
  32925. var PassPostProcess = (function (_super) {
  32926. __extends(PassPostProcess, _super);
  32927. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  32928. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32929. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  32930. }
  32931. return PassPostProcess;
  32932. }(BABYLON.PostProcess));
  32933. BABYLON.PassPostProcess = PassPostProcess;
  32934. })(BABYLON || (BABYLON = {}));
  32935. //# sourceMappingURL=babylon.passPostProcess.js.map
  32936. var BABYLON;
  32937. (function (BABYLON) {
  32938. var ShadowGenerator = (function () {
  32939. /**
  32940. * Creates a ShadowGenerator object.
  32941. * A ShadowGenerator is the required tool to use the shadows.
  32942. * Each light casting shadows needs to use its own ShadowGenerator.
  32943. * Required parameters :
  32944. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  32945. * - `light`: the light object generating the shadows.
  32946. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  32947. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  32948. */
  32949. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  32950. // Members
  32951. this._bias = 0.00005;
  32952. this._blurBoxOffset = 1;
  32953. this._blurScale = 2;
  32954. this._blurKernel = 1;
  32955. this._useKernelBlur = false;
  32956. this._filter = ShadowGenerator.FILTER_NONE;
  32957. this._darkness = 0;
  32958. this._transparencyShadow = false;
  32959. this.forceBackFacesOnly = false;
  32960. this._lightDirection = BABYLON.Vector3.Zero();
  32961. this._viewMatrix = BABYLON.Matrix.Zero();
  32962. this._projectionMatrix = BABYLON.Matrix.Zero();
  32963. this._transformMatrix = BABYLON.Matrix.Zero();
  32964. this._worldViewProjection = BABYLON.Matrix.Zero();
  32965. this._currentFaceIndex = 0;
  32966. this._currentFaceIndexCache = 0;
  32967. this._isCube = false;
  32968. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  32969. this._mapSize = mapSize;
  32970. this._light = light;
  32971. this._scene = light.getScene();
  32972. light._shadowGenerator = this;
  32973. // Texture type fallback from float to int if not supported.
  32974. var caps = this._scene.getEngine().getCaps();
  32975. if (!useFullFloatFirst) {
  32976. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  32977. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32978. }
  32979. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  32980. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  32981. }
  32982. else {
  32983. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32984. }
  32985. }
  32986. else {
  32987. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  32988. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  32989. }
  32990. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  32991. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32992. }
  32993. else {
  32994. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32995. }
  32996. }
  32997. this._initializeGenerator();
  32998. }
  32999. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  33000. // Static
  33001. get: function () {
  33002. return ShadowGenerator._FILTER_NONE;
  33003. },
  33004. enumerable: true,
  33005. configurable: true
  33006. });
  33007. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  33008. get: function () {
  33009. return ShadowGenerator._FILTER_POISSONSAMPLING;
  33010. },
  33011. enumerable: true,
  33012. configurable: true
  33013. });
  33014. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  33015. get: function () {
  33016. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  33017. },
  33018. enumerable: true,
  33019. configurable: true
  33020. });
  33021. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  33022. get: function () {
  33023. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  33024. },
  33025. enumerable: true,
  33026. configurable: true
  33027. });
  33028. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  33029. get: function () {
  33030. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33031. },
  33032. enumerable: true,
  33033. configurable: true
  33034. });
  33035. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  33036. get: function () {
  33037. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33038. },
  33039. enumerable: true,
  33040. configurable: true
  33041. });
  33042. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  33043. get: function () {
  33044. return this._bias;
  33045. },
  33046. set: function (bias) {
  33047. this._bias = bias;
  33048. },
  33049. enumerable: true,
  33050. configurable: true
  33051. });
  33052. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  33053. get: function () {
  33054. return this._blurBoxOffset;
  33055. },
  33056. set: function (value) {
  33057. if (this._blurBoxOffset === value) {
  33058. return;
  33059. }
  33060. this._blurBoxOffset = value;
  33061. this._disposeBlurPostProcesses();
  33062. },
  33063. enumerable: true,
  33064. configurable: true
  33065. });
  33066. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  33067. get: function () {
  33068. return this._blurScale;
  33069. },
  33070. set: function (value) {
  33071. if (this._blurScale === value) {
  33072. return;
  33073. }
  33074. this._blurScale = value;
  33075. this._disposeBlurPostProcesses();
  33076. },
  33077. enumerable: true,
  33078. configurable: true
  33079. });
  33080. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  33081. get: function () {
  33082. return this._blurKernel;
  33083. },
  33084. set: function (value) {
  33085. if (this._blurKernel === value) {
  33086. return;
  33087. }
  33088. this._blurKernel = value;
  33089. this._disposeBlurPostProcesses();
  33090. },
  33091. enumerable: true,
  33092. configurable: true
  33093. });
  33094. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  33095. get: function () {
  33096. return this._useKernelBlur;
  33097. },
  33098. set: function (value) {
  33099. if (this._useKernelBlur === value) {
  33100. return;
  33101. }
  33102. this._useKernelBlur = value;
  33103. this._disposeBlurPostProcesses();
  33104. },
  33105. enumerable: true,
  33106. configurable: true
  33107. });
  33108. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  33109. get: function () {
  33110. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  33111. },
  33112. set: function (value) {
  33113. this._depthScale = value;
  33114. },
  33115. enumerable: true,
  33116. configurable: true
  33117. });
  33118. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  33119. get: function () {
  33120. return this._filter;
  33121. },
  33122. set: function (value) {
  33123. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  33124. if (this._light.needCube()) {
  33125. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  33126. this.useExponentialShadowMap = true;
  33127. return;
  33128. }
  33129. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  33130. this.useCloseExponentialShadowMap = true;
  33131. return;
  33132. }
  33133. }
  33134. if (this._filter === value) {
  33135. return;
  33136. }
  33137. this._filter = value;
  33138. this._disposeBlurPostProcesses();
  33139. this._applyFilterValues();
  33140. this._light._markMeshesAsLightDirty();
  33141. },
  33142. enumerable: true,
  33143. configurable: true
  33144. });
  33145. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  33146. get: function () {
  33147. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  33148. },
  33149. set: function (value) {
  33150. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  33151. },
  33152. enumerable: true,
  33153. configurable: true
  33154. });
  33155. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  33156. get: function () {
  33157. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33158. return this.useExponentialShadowMap;
  33159. },
  33160. set: function (value) {
  33161. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33162. this.useExponentialShadowMap = value;
  33163. },
  33164. enumerable: true,
  33165. configurable: true
  33166. });
  33167. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  33168. get: function () {
  33169. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33170. return this.useBlurExponentialShadowMap;
  33171. },
  33172. set: function (value) {
  33173. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33174. this.useBlurExponentialShadowMap = value;
  33175. },
  33176. enumerable: true,
  33177. configurable: true
  33178. });
  33179. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  33180. get: function () {
  33181. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  33182. },
  33183. set: function (value) {
  33184. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33185. },
  33186. enumerable: true,
  33187. configurable: true
  33188. });
  33189. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  33190. get: function () {
  33191. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  33192. },
  33193. set: function (value) {
  33194. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33195. },
  33196. enumerable: true,
  33197. configurable: true
  33198. });
  33199. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  33200. get: function () {
  33201. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33202. },
  33203. set: function (value) {
  33204. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33205. },
  33206. enumerable: true,
  33207. configurable: true
  33208. });
  33209. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  33210. get: function () {
  33211. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33212. },
  33213. set: function (value) {
  33214. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33215. },
  33216. enumerable: true,
  33217. configurable: true
  33218. });
  33219. /**
  33220. * Returns the darkness value (float).
  33221. */
  33222. ShadowGenerator.prototype.getDarkness = function () {
  33223. return this._darkness;
  33224. };
  33225. /**
  33226. * Sets the ShadowGenerator darkness value (float <= 1.0).
  33227. * Returns the ShadowGenerator.
  33228. */
  33229. ShadowGenerator.prototype.setDarkness = function (darkness) {
  33230. if (darkness >= 1.0)
  33231. this._darkness = 1.0;
  33232. else if (darkness <= 0.0)
  33233. this._darkness = 0.0;
  33234. else
  33235. this._darkness = darkness;
  33236. return this;
  33237. };
  33238. /**
  33239. * Sets the ability to have transparent shadow (boolean).
  33240. * Returns the ShadowGenerator.
  33241. */
  33242. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  33243. this._transparencyShadow = hasShadow;
  33244. return this;
  33245. };
  33246. /**
  33247. * Returns a RenderTargetTexture object : the shadow map texture.
  33248. */
  33249. ShadowGenerator.prototype.getShadowMap = function () {
  33250. return this._shadowMap;
  33251. };
  33252. /**
  33253. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  33254. */
  33255. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  33256. if (this._shadowMap2) {
  33257. return this._shadowMap2;
  33258. }
  33259. return this._shadowMap;
  33260. };
  33261. /**
  33262. * Returns the associated light object.
  33263. */
  33264. ShadowGenerator.prototype.getLight = function () {
  33265. return this._light;
  33266. };
  33267. ShadowGenerator.prototype._initializeGenerator = function () {
  33268. this._light._markMeshesAsLightDirty();
  33269. this._initializeShadowMap();
  33270. };
  33271. ShadowGenerator.prototype._initializeShadowMap = function () {
  33272. var _this = this;
  33273. // Render target
  33274. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  33275. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33276. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33277. this._shadowMap.anisotropicFilteringLevel = 1;
  33278. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33279. this._shadowMap.renderParticles = false;
  33280. // Record Face Index before render.
  33281. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  33282. _this._currentFaceIndex = faceIndex;
  33283. });
  33284. // Custom render function.
  33285. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  33286. // Blur if required afer render.
  33287. this._shadowMap.onAfterUnbindObservable.add(function () {
  33288. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  33289. return;
  33290. }
  33291. if (!_this._blurPostProcesses) {
  33292. _this._initializeBlurRTTAndPostProcesses();
  33293. }
  33294. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  33295. });
  33296. // Clear according to the chosen filter.
  33297. this._shadowMap.onClearObservable.add(function (engine) {
  33298. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  33299. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  33300. }
  33301. else {
  33302. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  33303. }
  33304. });
  33305. };
  33306. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  33307. var _this = this;
  33308. var engine = this._scene.getEngine();
  33309. var targetSize = this._mapSize / this.blurScale;
  33310. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  33311. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  33312. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33313. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33314. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33315. }
  33316. if (this.useKernelBlur) {
  33317. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33318. this._kernelBlurXPostprocess.width = targetSize;
  33319. this._kernelBlurXPostprocess.height = targetSize;
  33320. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  33321. effect.setTexture("textureSampler", _this._shadowMap);
  33322. });
  33323. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33324. this._kernelBlurXPostprocess.autoClear = false;
  33325. this._kernelBlurYPostprocess.autoClear = false;
  33326. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33327. this._kernelBlurXPostprocess.packedFloat = true;
  33328. this._kernelBlurYPostprocess.packedFloat = true;
  33329. }
  33330. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  33331. }
  33332. else {
  33333. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  33334. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  33335. effect.setFloat2("screenSize", targetSize, targetSize);
  33336. effect.setTexture("textureSampler", _this._shadowMap);
  33337. });
  33338. this._boxBlurPostprocess.autoClear = false;
  33339. this._blurPostProcesses = [this._boxBlurPostprocess];
  33340. }
  33341. };
  33342. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33343. var index;
  33344. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33345. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  33346. }
  33347. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33348. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  33349. }
  33350. if (this._transparencyShadow) {
  33351. for (index = 0; index < transparentSubMeshes.length; index++) {
  33352. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  33353. }
  33354. }
  33355. };
  33356. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  33357. var _this = this;
  33358. var mesh = subMesh.getRenderingMesh();
  33359. var scene = this._scene;
  33360. var engine = scene.getEngine();
  33361. // Culling
  33362. engine.setState(subMesh.getMaterial().backFaceCulling);
  33363. // Managing instances
  33364. var batch = mesh._getInstancesRenderList(subMesh._id);
  33365. if (batch.mustReturn) {
  33366. return;
  33367. }
  33368. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33369. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  33370. engine.enableEffect(this._effect);
  33371. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33372. var material = subMesh.getMaterial();
  33373. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  33374. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  33375. this._effect.setVector3("lightPosition", this.getLight().position);
  33376. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  33377. // Alpha test
  33378. if (material && material.needAlphaTesting()) {
  33379. var alphaTexture = material.getAlphaTestTexture();
  33380. if (alphaTexture) {
  33381. this._effect.setTexture("diffuseSampler", alphaTexture);
  33382. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  33383. }
  33384. }
  33385. // Bones
  33386. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33387. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33388. }
  33389. if (this.forceBackFacesOnly) {
  33390. engine.setState(true, 0, false, true);
  33391. }
  33392. // Draw
  33393. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33394. if (this.forceBackFacesOnly) {
  33395. engine.setState(true, 0, false, false);
  33396. }
  33397. }
  33398. else {
  33399. // Need to reset refresh rate of the shadowMap
  33400. this._shadowMap.resetRefreshCounter();
  33401. }
  33402. };
  33403. ShadowGenerator.prototype._applyFilterValues = function () {
  33404. if (this.filter === ShadowGenerator.FILTER_NONE) {
  33405. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  33406. }
  33407. else {
  33408. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33409. }
  33410. };
  33411. /**
  33412. * Boolean : true when the ShadowGenerator is finally computed.
  33413. */
  33414. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  33415. var defines = [];
  33416. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33417. defines.push("#define FLOAT");
  33418. }
  33419. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33420. defines.push("#define ESM");
  33421. }
  33422. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33423. var mesh = subMesh.getMesh();
  33424. var material = subMesh.getMaterial();
  33425. // Alpha test
  33426. if (material && material.needAlphaTesting()) {
  33427. var alphaTexture = material.getAlphaTestTexture();
  33428. if (alphaTexture) {
  33429. defines.push("#define ALPHATEST");
  33430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33431. attribs.push(BABYLON.VertexBuffer.UVKind);
  33432. defines.push("#define UV1");
  33433. }
  33434. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33435. if (alphaTexture.coordinatesIndex === 1) {
  33436. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33437. defines.push("#define UV2");
  33438. }
  33439. }
  33440. }
  33441. }
  33442. // Bones
  33443. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33444. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33445. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33446. if (mesh.numBoneInfluencers > 4) {
  33447. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33448. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33449. }
  33450. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33451. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33452. }
  33453. else {
  33454. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33455. }
  33456. // Instances
  33457. if (useInstances) {
  33458. defines.push("#define INSTANCES");
  33459. attribs.push("world0");
  33460. attribs.push("world1");
  33461. attribs.push("world2");
  33462. attribs.push("world3");
  33463. }
  33464. // Get correct effect
  33465. var join = defines.join("\n");
  33466. if (this._cachedDefines !== join) {
  33467. this._cachedDefines = join;
  33468. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  33469. }
  33470. return this._effect.isReady();
  33471. };
  33472. /**
  33473. * This creates the defines related to the standard BJS materials.
  33474. */
  33475. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  33476. var scene = this._scene;
  33477. var light = this._light;
  33478. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33479. return;
  33480. }
  33481. defines["SHADOW" + lightIndex] = true;
  33482. if (this.usePoissonSampling) {
  33483. defines["SHADOWPCF" + lightIndex] = true;
  33484. }
  33485. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33486. defines["SHADOWESM" + lightIndex] = true;
  33487. }
  33488. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  33489. defines["SHADOWCLOSEESM" + lightIndex] = true;
  33490. }
  33491. if (light.needCube()) {
  33492. defines["SHADOWCUBE" + lightIndex] = true;
  33493. }
  33494. };
  33495. /**
  33496. * This binds shadow lights related to the standard BJS materials.
  33497. * It implies the unifroms available on the materials are the standard BJS ones.
  33498. */
  33499. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  33500. var light = this._light;
  33501. var scene = this._scene;
  33502. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33503. return;
  33504. }
  33505. if (!light.needCube()) {
  33506. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  33507. }
  33508. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  33509. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  33510. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  33511. };
  33512. // Methods
  33513. /**
  33514. * Returns a Matrix object : the updated transformation matrix.
  33515. */
  33516. ShadowGenerator.prototype.getTransformMatrix = function () {
  33517. var scene = this._scene;
  33518. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  33519. return this._transformMatrix;
  33520. }
  33521. this._currentRenderID = scene.getRenderId();
  33522. this._currentFaceIndexCache = this._currentFaceIndex;
  33523. var lightPosition = this._light.position;
  33524. if (this._light.computeTransformedInformation()) {
  33525. lightPosition = this._light.transformedPosition;
  33526. }
  33527. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  33528. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  33529. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  33530. }
  33531. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  33532. this._cachedPosition = lightPosition.clone();
  33533. this._cachedDirection = this._lightDirection.clone();
  33534. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  33535. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  33536. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  33537. }
  33538. return this._transformMatrix;
  33539. };
  33540. ShadowGenerator.prototype.recreateShadowMap = function () {
  33541. // Track render list.
  33542. var renderList = this._shadowMap.renderList;
  33543. // Clean up existing data.
  33544. this._disposeRTTandPostProcesses();
  33545. // Reinitializes.
  33546. this._initializeGenerator();
  33547. // Reaffect the filter to ensure a correct fallback if necessary.
  33548. this.filter = this.filter;
  33549. // Reaffect the filter.
  33550. this._applyFilterValues();
  33551. // Reaffect Render List.
  33552. this._shadowMap.renderList = renderList;
  33553. };
  33554. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  33555. if (this._shadowMap2) {
  33556. this._shadowMap2.dispose();
  33557. this._shadowMap2 = null;
  33558. }
  33559. if (this._downSamplePostprocess) {
  33560. this._downSamplePostprocess.dispose();
  33561. this._downSamplePostprocess = null;
  33562. }
  33563. if (this._boxBlurPostprocess) {
  33564. this._boxBlurPostprocess.dispose();
  33565. this._boxBlurPostprocess = null;
  33566. }
  33567. if (this._kernelBlurXPostprocess) {
  33568. this._kernelBlurXPostprocess.dispose();
  33569. this._kernelBlurXPostprocess = null;
  33570. }
  33571. if (this._kernelBlurYPostprocess) {
  33572. this._kernelBlurYPostprocess.dispose();
  33573. this._kernelBlurYPostprocess = null;
  33574. }
  33575. this._blurPostProcesses = null;
  33576. };
  33577. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  33578. if (this._shadowMap) {
  33579. this._shadowMap.dispose();
  33580. this._shadowMap = null;
  33581. }
  33582. this._disposeBlurPostProcesses();
  33583. };
  33584. /**
  33585. * Disposes the ShadowGenerator.
  33586. * Returns nothing.
  33587. */
  33588. ShadowGenerator.prototype.dispose = function () {
  33589. this._disposeRTTandPostProcesses();
  33590. this._light._shadowGenerator = null;
  33591. this._light._markMeshesAsLightDirty();
  33592. };
  33593. /**
  33594. * Serializes the ShadowGenerator and returns a serializationObject.
  33595. */
  33596. ShadowGenerator.prototype.serialize = function () {
  33597. var serializationObject = {};
  33598. var shadowMap = this.getShadowMap();
  33599. serializationObject.lightId = this._light.id;
  33600. serializationObject.mapSize = shadowMap.getRenderSize();
  33601. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  33602. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  33603. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33604. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33605. serializationObject.usePoissonSampling = this.usePoissonSampling;
  33606. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  33607. serializationObject.depthScale = this.depthScale;
  33608. serializationObject.darkness = this.getDarkness();
  33609. serializationObject.blurBoxOffset = this.blurBoxOffset;
  33610. serializationObject.blurKernel = this.blurKernel;
  33611. serializationObject.blurScale = this.blurScale;
  33612. serializationObject.useKernelBlur = this.useKernelBlur;
  33613. serializationObject.transparencyShadow = this._transparencyShadow;
  33614. serializationObject.renderList = [];
  33615. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  33616. var mesh = shadowMap.renderList[meshIndex];
  33617. serializationObject.renderList.push(mesh.id);
  33618. }
  33619. return serializationObject;
  33620. };
  33621. /**
  33622. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  33623. */
  33624. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  33625. //casting to point light, as light is missing the position attr and typescript complains.
  33626. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  33627. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  33628. var shadowMap = shadowGenerator.getShadowMap();
  33629. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  33630. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  33631. meshes.forEach(function (mesh) {
  33632. shadowMap.renderList.push(mesh);
  33633. });
  33634. }
  33635. if (parsedShadowGenerator.usePoissonSampling) {
  33636. shadowGenerator.usePoissonSampling = true;
  33637. }
  33638. else if (parsedShadowGenerator.useExponentialShadowMap) {
  33639. shadowGenerator.useExponentialShadowMap = true;
  33640. }
  33641. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33642. shadowGenerator.useBlurExponentialShadowMap = true;
  33643. }
  33644. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  33645. shadowGenerator.useCloseExponentialShadowMap = true;
  33646. }
  33647. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33648. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  33649. }
  33650. else if (parsedShadowGenerator.useVarianceShadowMap) {
  33651. shadowGenerator.useExponentialShadowMap = true;
  33652. }
  33653. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  33654. shadowGenerator.useBlurExponentialShadowMap = true;
  33655. }
  33656. if (parsedShadowGenerator.depthScale) {
  33657. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  33658. }
  33659. if (parsedShadowGenerator.blurScale) {
  33660. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  33661. }
  33662. if (parsedShadowGenerator.blurBoxOffset) {
  33663. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  33664. }
  33665. if (parsedShadowGenerator.useKernelBlur) {
  33666. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  33667. }
  33668. if (parsedShadowGenerator.blurKernel) {
  33669. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  33670. }
  33671. if (parsedShadowGenerator.bias !== undefined) {
  33672. shadowGenerator.bias = parsedShadowGenerator.bias;
  33673. }
  33674. if (parsedShadowGenerator.darkness) {
  33675. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  33676. }
  33677. if (parsedShadowGenerator.transparencyShadow) {
  33678. shadowGenerator.setTransparencyShadow(true);
  33679. }
  33680. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  33681. return shadowGenerator;
  33682. };
  33683. return ShadowGenerator;
  33684. }());
  33685. ShadowGenerator._FILTER_NONE = 0;
  33686. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  33687. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  33688. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  33689. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  33690. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  33691. BABYLON.ShadowGenerator = ShadowGenerator;
  33692. })(BABYLON || (BABYLON = {}));
  33693. //# sourceMappingURL=babylon.shadowGenerator.js.map
  33694. var BABYLON;
  33695. (function (BABYLON) {
  33696. var ShadowLight = (function (_super) {
  33697. __extends(ShadowLight, _super);
  33698. function ShadowLight() {
  33699. var _this = _super !== null && _super.apply(this, arguments) || this;
  33700. _this._needProjectionMatrixCompute = true;
  33701. return _this;
  33702. }
  33703. Object.defineProperty(ShadowLight.prototype, "direction", {
  33704. get: function () {
  33705. return this._direction;
  33706. },
  33707. set: function (value) {
  33708. this._direction = value;
  33709. },
  33710. enumerable: true,
  33711. configurable: true
  33712. });
  33713. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33714. get: function () {
  33715. return this._shadowMinZ;
  33716. },
  33717. set: function (value) {
  33718. this._shadowMinZ = value;
  33719. this.forceProjectionMatrixCompute();
  33720. },
  33721. enumerable: true,
  33722. configurable: true
  33723. });
  33724. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33725. get: function () {
  33726. return this._shadowMaxZ;
  33727. },
  33728. set: function (value) {
  33729. this._shadowMaxZ = value;
  33730. this.forceProjectionMatrixCompute();
  33731. },
  33732. enumerable: true,
  33733. configurable: true
  33734. });
  33735. /**
  33736. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33737. */
  33738. ShadowLight.prototype.computeTransformedInformation = function () {
  33739. if (this.parent && this.parent.getWorldMatrix) {
  33740. if (!this.transformedPosition) {
  33741. this.transformedPosition = BABYLON.Vector3.Zero();
  33742. }
  33743. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33744. // In case the direction is present.
  33745. if (this.direction) {
  33746. if (!this.transformedDirection) {
  33747. this.transformedDirection = BABYLON.Vector3.Zero();
  33748. }
  33749. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33750. }
  33751. return true;
  33752. }
  33753. return false;
  33754. };
  33755. /**
  33756. * Return the depth scale used for the shadow map.
  33757. */
  33758. ShadowLight.prototype.getDepthScale = function () {
  33759. return 50.0;
  33760. };
  33761. /**
  33762. * Returns the light direction (Vector3) for any passed face index.
  33763. */
  33764. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33765. return this.transformedDirection ? this.transformedDirection : this.direction;
  33766. };
  33767. /**
  33768. * Returns the DirectionalLight absolute position in the World.
  33769. */
  33770. ShadowLight.prototype.getAbsolutePosition = function () {
  33771. return this.transformedPosition ? this.transformedPosition : this.position;
  33772. };
  33773. /**
  33774. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33775. * Returns the updated DirectionalLight direction (Vector3).
  33776. */
  33777. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33778. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33779. return this.direction;
  33780. };
  33781. /**
  33782. * Returns the light rotation (Vector3).
  33783. */
  33784. ShadowLight.prototype.getRotation = function () {
  33785. this.direction.normalize();
  33786. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33787. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33788. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33789. };
  33790. /**
  33791. * Boolean : false by default.
  33792. */
  33793. ShadowLight.prototype.needCube = function () {
  33794. return false;
  33795. };
  33796. /**
  33797. * Specifies wether or not the projection matrix should be recomputed this frame.
  33798. */
  33799. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33800. return this._needProjectionMatrixCompute;
  33801. };
  33802. /**
  33803. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33804. */
  33805. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33806. this._needProjectionMatrixCompute = true;
  33807. };
  33808. /**
  33809. * Get the world matrix of the sahdow lights.
  33810. */
  33811. ShadowLight.prototype._getWorldMatrix = function () {
  33812. if (!this._worldMatrix) {
  33813. this._worldMatrix = BABYLON.Matrix.Identity();
  33814. }
  33815. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33816. return this._worldMatrix;
  33817. };
  33818. /**
  33819. * Gets the minZ used for shadow according to both the scene and the light.
  33820. * @param activeCamera
  33821. */
  33822. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33823. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33824. };
  33825. /**
  33826. * Gets the maxZ used for shadow according to both the scene and the light.
  33827. * @param activeCamera
  33828. */
  33829. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  33830. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  33831. };
  33832. /**
  33833. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33834. * Returns the light.
  33835. */
  33836. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33837. if (this.customProjectionMatrixBuilder) {
  33838. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33839. }
  33840. else {
  33841. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33842. }
  33843. return this;
  33844. };
  33845. return ShadowLight;
  33846. }(BABYLON.Light));
  33847. __decorate([
  33848. BABYLON.serializeAsVector3()
  33849. ], ShadowLight.prototype, "position", void 0);
  33850. __decorate([
  33851. BABYLON.serializeAsVector3()
  33852. ], ShadowLight.prototype, "direction", null);
  33853. __decorate([
  33854. BABYLON.serialize()
  33855. ], ShadowLight.prototype, "shadowMinZ", null);
  33856. __decorate([
  33857. BABYLON.serialize()
  33858. ], ShadowLight.prototype, "shadowMaxZ", null);
  33859. BABYLON.ShadowLight = ShadowLight;
  33860. })(BABYLON || (BABYLON = {}));
  33861. //# sourceMappingURL=babylon.shadowLight.js.map
  33862. var BABYLON;
  33863. (function (BABYLON) {
  33864. var PointLight = (function (_super) {
  33865. __extends(PointLight, _super);
  33866. /**
  33867. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33868. * A PointLight emits the light in every direction.
  33869. * It can cast shadows.
  33870. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33871. * ```javascript
  33872. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33873. * ```
  33874. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33875. */
  33876. function PointLight(name, position, scene) {
  33877. var _this = _super.call(this, name, scene) || this;
  33878. _this._shadowAngle = Math.PI / 2;
  33879. _this.position = position;
  33880. return _this;
  33881. }
  33882. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33883. /**
  33884. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33885. * This specifies what angle the shadow will use to be created.
  33886. *
  33887. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33888. */
  33889. get: function () {
  33890. return this._shadowAngle;
  33891. },
  33892. /**
  33893. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33894. * This specifies what angle the shadow will use to be created.
  33895. *
  33896. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33897. */
  33898. set: function (value) {
  33899. this._shadowAngle = value;
  33900. this.forceProjectionMatrixCompute();
  33901. },
  33902. enumerable: true,
  33903. configurable: true
  33904. });
  33905. Object.defineProperty(PointLight.prototype, "direction", {
  33906. get: function () {
  33907. return this._direction;
  33908. },
  33909. /**
  33910. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33911. */
  33912. set: function (value) {
  33913. var previousNeedCube = this.needCube();
  33914. this._direction = value;
  33915. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33916. this._shadowGenerator.recreateShadowMap();
  33917. }
  33918. },
  33919. enumerable: true,
  33920. configurable: true
  33921. });
  33922. /**
  33923. * Returns the string "PointLight"
  33924. */
  33925. PointLight.prototype.getClassName = function () {
  33926. return "PointLight";
  33927. };
  33928. /**
  33929. * Returns the integer 0.
  33930. */
  33931. PointLight.prototype.getTypeID = function () {
  33932. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33933. };
  33934. /**
  33935. * Specifies wether or not the shadowmap should be a cube texture.
  33936. */
  33937. PointLight.prototype.needCube = function () {
  33938. return !this.direction;
  33939. };
  33940. /**
  33941. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33942. */
  33943. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33944. if (this.direction) {
  33945. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33946. }
  33947. else {
  33948. switch (faceIndex) {
  33949. case 0:
  33950. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33951. case 1:
  33952. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33953. case 2:
  33954. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33955. case 3:
  33956. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33957. case 4:
  33958. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33959. case 5:
  33960. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33961. }
  33962. }
  33963. return BABYLON.Vector3.Zero();
  33964. };
  33965. /**
  33966. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33967. * - fov = PI / 2
  33968. * - aspect ratio : 1.0
  33969. * - z-near and far equal to the active camera minZ and maxZ.
  33970. * Returns the PointLight.
  33971. */
  33972. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33973. var activeCamera = this.getScene().activeCamera;
  33974. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  33975. };
  33976. PointLight.prototype._buildUniformLayout = function () {
  33977. this._uniformBuffer.addUniform("vLightData", 4);
  33978. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33979. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33980. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33981. this._uniformBuffer.addUniform("depthValues", 2);
  33982. this._uniformBuffer.create();
  33983. };
  33984. /**
  33985. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  33986. * Returns the PointLight.
  33987. */
  33988. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  33989. if (this.computeTransformedInformation()) {
  33990. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  33991. return this;
  33992. }
  33993. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  33994. return this;
  33995. };
  33996. return PointLight;
  33997. }(BABYLON.ShadowLight));
  33998. __decorate([
  33999. BABYLON.serialize()
  34000. ], PointLight.prototype, "shadowAngle", null);
  34001. BABYLON.PointLight = PointLight;
  34002. })(BABYLON || (BABYLON = {}));
  34003. //# sourceMappingURL=babylon.pointLight.js.map
  34004. /// <reference path="babylon.light.ts" />
  34005. var BABYLON;
  34006. (function (BABYLON) {
  34007. var DirectionalLight = (function (_super) {
  34008. __extends(DirectionalLight, _super);
  34009. /**
  34010. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34011. * The directional light is emitted from everywhere in the given direction.
  34012. * It can cast shawdows.
  34013. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34014. */
  34015. function DirectionalLight(name, direction, scene) {
  34016. var _this = _super.call(this, name, scene) || this;
  34017. _this._shadowFrustumSize = 0;
  34018. _this._shadowOrthoScale = 0.5;
  34019. _this.autoUpdateExtends = true;
  34020. // Cache
  34021. _this._orthoLeft = Number.MAX_VALUE;
  34022. _this._orthoRight = Number.MIN_VALUE;
  34023. _this._orthoTop = Number.MIN_VALUE;
  34024. _this._orthoBottom = Number.MAX_VALUE;
  34025. _this.position = direction.scale(-1.0);
  34026. _this.direction = direction;
  34027. return _this;
  34028. }
  34029. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34030. /**
  34031. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34032. */
  34033. get: function () {
  34034. return this._shadowFrustumSize;
  34035. },
  34036. /**
  34037. * Specifies a fix frustum size for the shadow generation.
  34038. */
  34039. set: function (value) {
  34040. this._shadowFrustumSize = value;
  34041. this.forceProjectionMatrixCompute();
  34042. },
  34043. enumerable: true,
  34044. configurable: true
  34045. });
  34046. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34047. get: function () {
  34048. return this._shadowOrthoScale;
  34049. },
  34050. set: function (value) {
  34051. this._shadowOrthoScale = value;
  34052. this.forceProjectionMatrixCompute();
  34053. },
  34054. enumerable: true,
  34055. configurable: true
  34056. });
  34057. /**
  34058. * Returns the string "DirectionalLight".
  34059. */
  34060. DirectionalLight.prototype.getClassName = function () {
  34061. return "DirectionalLight";
  34062. };
  34063. /**
  34064. * Returns the integer 1.
  34065. */
  34066. DirectionalLight.prototype.getTypeID = function () {
  34067. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34068. };
  34069. /**
  34070. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34071. * Returns the DirectionalLight Shadow projection matrix.
  34072. */
  34073. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34074. if (this.shadowFrustumSize > 0) {
  34075. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34076. }
  34077. else {
  34078. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34079. }
  34080. };
  34081. /**
  34082. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34083. * Returns the DirectionalLight Shadow projection matrix.
  34084. */
  34085. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34086. var activeCamera = this.getScene().activeCamera;
  34087. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34088. };
  34089. /**
  34090. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34091. * Returns the DirectionalLight Shadow projection matrix.
  34092. */
  34093. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34094. var activeCamera = this.getScene().activeCamera;
  34095. // Check extends
  34096. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34097. var tempVector3 = BABYLON.Vector3.Zero();
  34098. this._orthoLeft = Number.MAX_VALUE;
  34099. this._orthoRight = Number.MIN_VALUE;
  34100. this._orthoTop = Number.MIN_VALUE;
  34101. this._orthoBottom = Number.MAX_VALUE;
  34102. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34103. var mesh = renderList[meshIndex];
  34104. if (!mesh) {
  34105. continue;
  34106. }
  34107. var boundingInfo = mesh.getBoundingInfo();
  34108. if (!boundingInfo) {
  34109. continue;
  34110. }
  34111. var boundingBox = boundingInfo.boundingBox;
  34112. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34113. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34114. if (tempVector3.x < this._orthoLeft)
  34115. this._orthoLeft = tempVector3.x;
  34116. if (tempVector3.y < this._orthoBottom)
  34117. this._orthoBottom = tempVector3.y;
  34118. if (tempVector3.x > this._orthoRight)
  34119. this._orthoRight = tempVector3.x;
  34120. if (tempVector3.y > this._orthoTop)
  34121. this._orthoTop = tempVector3.y;
  34122. }
  34123. }
  34124. }
  34125. var xOffset = this._orthoRight - this._orthoLeft;
  34126. var yOffset = this._orthoTop - this._orthoBottom;
  34127. 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);
  34128. };
  34129. DirectionalLight.prototype._buildUniformLayout = function () {
  34130. this._uniformBuffer.addUniform("vLightData", 4);
  34131. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34132. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34133. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34134. this._uniformBuffer.addUniform("depthValues", 2);
  34135. this._uniformBuffer.create();
  34136. };
  34137. /**
  34138. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34139. * Returns the DirectionalLight.
  34140. */
  34141. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34142. if (this.computeTransformedInformation()) {
  34143. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34144. return this;
  34145. }
  34146. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34147. return this;
  34148. };
  34149. /**
  34150. * Gets the minZ used for shadow according to both the scene and the light.
  34151. *
  34152. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34153. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34154. * @param activeCamera
  34155. */
  34156. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34157. return 1;
  34158. };
  34159. /**
  34160. * Gets the maxZ used for shadow according to both the scene and the light.
  34161. *
  34162. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34163. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34164. * @param activeCamera
  34165. */
  34166. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34167. return 1;
  34168. };
  34169. return DirectionalLight;
  34170. }(BABYLON.ShadowLight));
  34171. __decorate([
  34172. BABYLON.serialize()
  34173. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34174. __decorate([
  34175. BABYLON.serialize()
  34176. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34177. __decorate([
  34178. BABYLON.serialize()
  34179. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34180. BABYLON.DirectionalLight = DirectionalLight;
  34181. })(BABYLON || (BABYLON = {}));
  34182. //# sourceMappingURL=babylon.directionalLight.js.map
  34183. var BABYLON;
  34184. (function (BABYLON) {
  34185. var SpotLight = (function (_super) {
  34186. __extends(SpotLight, _super);
  34187. /**
  34188. * Creates a SpotLight object in the scene with the passed parameters :
  34189. * - `position` (Vector3) is the initial SpotLight position,
  34190. * - `direction` (Vector3) is the initial SpotLight direction,
  34191. * - `angle` (float, in radians) is the spot light cone angle,
  34192. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34193. * A spot light is a simply light oriented cone.
  34194. * It can cast shadows.
  34195. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34196. */
  34197. function SpotLight(name, position, direction, angle, exponent, scene) {
  34198. var _this = _super.call(this, name, scene) || this;
  34199. _this.position = position;
  34200. _this.direction = direction;
  34201. _this.angle = angle;
  34202. _this.exponent = exponent;
  34203. return _this;
  34204. }
  34205. Object.defineProperty(SpotLight.prototype, "angle", {
  34206. get: function () {
  34207. return this._angle;
  34208. },
  34209. set: function (value) {
  34210. this._angle = value;
  34211. this.forceProjectionMatrixCompute();
  34212. },
  34213. enumerable: true,
  34214. configurable: true
  34215. });
  34216. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34217. get: function () {
  34218. return this._shadowAngleScale;
  34219. },
  34220. /**
  34221. * Allows scaling the angle of the light for shadow generation only.
  34222. */
  34223. set: function (value) {
  34224. this._shadowAngleScale = value;
  34225. this.forceProjectionMatrixCompute();
  34226. },
  34227. enumerable: true,
  34228. configurable: true
  34229. });
  34230. /**
  34231. * Returns the string "SpotLight".
  34232. */
  34233. SpotLight.prototype.getClassName = function () {
  34234. return "SpotLight";
  34235. };
  34236. /**
  34237. * Returns the integer 2.
  34238. */
  34239. SpotLight.prototype.getTypeID = function () {
  34240. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34241. };
  34242. /**
  34243. * 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.
  34244. * Returns the SpotLight.
  34245. */
  34246. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34247. var activeCamera = this.getScene().activeCamera;
  34248. this._shadowAngleScale = this._shadowAngleScale || 1;
  34249. var angle = this._shadowAngleScale * this._angle;
  34250. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34251. };
  34252. SpotLight.prototype._buildUniformLayout = function () {
  34253. this._uniformBuffer.addUniform("vLightData", 4);
  34254. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34255. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34256. this._uniformBuffer.addUniform("vLightDirection", 3);
  34257. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34258. this._uniformBuffer.addUniform("depthValues", 2);
  34259. this._uniformBuffer.create();
  34260. };
  34261. /**
  34262. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34263. * Return the SpotLight.
  34264. */
  34265. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34266. var normalizeDirection;
  34267. if (this.computeTransformedInformation()) {
  34268. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34269. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34270. }
  34271. else {
  34272. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34273. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34274. }
  34275. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34276. return this;
  34277. };
  34278. return SpotLight;
  34279. }(BABYLON.ShadowLight));
  34280. __decorate([
  34281. BABYLON.serialize()
  34282. ], SpotLight.prototype, "angle", null);
  34283. __decorate([
  34284. BABYLON.serialize()
  34285. /**
  34286. * Allows scaling the angle of the light for shadow generation only.
  34287. */
  34288. ], SpotLight.prototype, "shadowAngleScale", null);
  34289. __decorate([
  34290. BABYLON.serialize()
  34291. ], SpotLight.prototype, "exponent", void 0);
  34292. BABYLON.SpotLight = SpotLight;
  34293. })(BABYLON || (BABYLON = {}));
  34294. //# sourceMappingURL=babylon.spotLight.js.map
  34295. var BABYLON;
  34296. (function (BABYLON) {
  34297. var MultiMaterial = (function (_super) {
  34298. __extends(MultiMaterial, _super);
  34299. function MultiMaterial(name, scene) {
  34300. var _this = _super.call(this, name, scene, true) || this;
  34301. scene.multiMaterials.push(_this);
  34302. _this.subMaterials = new Array();
  34303. return _this;
  34304. }
  34305. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  34306. get: function () {
  34307. return this._subMaterials;
  34308. },
  34309. set: function (value) {
  34310. this._subMaterials = value;
  34311. this._hookArray(value);
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. MultiMaterial.prototype._hookArray = function (array) {
  34317. var _this = this;
  34318. var oldPush = array.push;
  34319. array.push = function () {
  34320. var items = [];
  34321. for (var _i = 0; _i < arguments.length; _i++) {
  34322. items[_i] = arguments[_i];
  34323. }
  34324. var result = oldPush.apply(array, items);
  34325. _this._markAllSubMeshesAsTexturesDirty();
  34326. return result;
  34327. };
  34328. var oldSplice = array.splice;
  34329. array.splice = function (index, deleteCount) {
  34330. var deleted = oldSplice.apply(array, [index, deleteCount]);
  34331. _this._markAllSubMeshesAsTexturesDirty();
  34332. return deleted;
  34333. };
  34334. };
  34335. // Properties
  34336. MultiMaterial.prototype.getSubMaterial = function (index) {
  34337. if (index < 0 || index >= this.subMaterials.length) {
  34338. return this.getScene().defaultMaterial;
  34339. }
  34340. return this.subMaterials[index];
  34341. };
  34342. // Methods
  34343. MultiMaterial.prototype.getClassName = function () {
  34344. return "MultiMaterial";
  34345. };
  34346. MultiMaterial.prototype.isReady = function (mesh) {
  34347. for (var index = 0; index < this.subMaterials.length; index++) {
  34348. var subMaterial = this.subMaterials[index];
  34349. if (subMaterial) {
  34350. if (!this.subMaterials[index].isReady(mesh)) {
  34351. return false;
  34352. }
  34353. }
  34354. }
  34355. return true;
  34356. };
  34357. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  34358. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  34359. for (var index = 0; index < this.subMaterials.length; index++) {
  34360. var subMaterial = null;
  34361. if (cloneChildren) {
  34362. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  34363. }
  34364. else {
  34365. subMaterial = this.subMaterials[index];
  34366. }
  34367. newMultiMaterial.subMaterials.push(subMaterial);
  34368. }
  34369. return newMultiMaterial;
  34370. };
  34371. MultiMaterial.prototype.serialize = function () {
  34372. var serializationObject = {};
  34373. serializationObject.name = this.name;
  34374. serializationObject.id = this.id;
  34375. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34376. serializationObject.materials = [];
  34377. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  34378. var subMat = this.subMaterials[matIndex];
  34379. if (subMat) {
  34380. serializationObject.materials.push(subMat.id);
  34381. }
  34382. else {
  34383. serializationObject.materials.push(null);
  34384. }
  34385. }
  34386. return serializationObject;
  34387. };
  34388. return MultiMaterial;
  34389. }(BABYLON.Material));
  34390. BABYLON.MultiMaterial = MultiMaterial;
  34391. })(BABYLON || (BABYLON = {}));
  34392. //# sourceMappingURL=babylon.multiMaterial.js.map
  34393. var BABYLON;
  34394. (function (BABYLON) {
  34395. var PBRMaterialDefines = (function (_super) {
  34396. __extends(PBRMaterialDefines, _super);
  34397. function PBRMaterialDefines() {
  34398. var _this = _super.call(this) || this;
  34399. _this.PBR = true;
  34400. _this.ALBEDO = false;
  34401. _this.AMBIENT = false;
  34402. _this.AMBIENTINGRAYSCALE = false;
  34403. _this.OPACITY = false;
  34404. _this.OPACITYRGB = false;
  34405. _this.REFLECTION = false;
  34406. _this.EMISSIVE = false;
  34407. _this.REFLECTIVITY = false;
  34408. _this.BUMP = false;
  34409. _this.PARALLAX = false;
  34410. _this.PARALLAXOCCLUSION = false;
  34411. _this.SPECULAROVERALPHA = false;
  34412. _this.CLIPPLANE = false;
  34413. _this.ALPHATEST = false;
  34414. _this.ALPHAFROMALBEDO = false;
  34415. _this.POINTSIZE = false;
  34416. _this.FOG = false;
  34417. _this.SPECULARTERM = false;
  34418. _this.OPACITYFRESNEL = false;
  34419. _this.EMISSIVEFRESNEL = false;
  34420. _this.FRESNEL = false;
  34421. _this.NORMAL = false;
  34422. _this.TANGENT = false;
  34423. _this.UV1 = false;
  34424. _this.UV2 = false;
  34425. _this.VERTEXCOLOR = false;
  34426. _this.VERTEXALPHA = false;
  34427. _this.NUM_BONE_INFLUENCERS = 0;
  34428. _this.BonesPerMesh = 0;
  34429. _this.INSTANCES = false;
  34430. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34431. _this.MICROSURFACEAUTOMATIC = false;
  34432. _this.EMISSIVEASILLUMINATION = false;
  34433. _this.LIGHTMAP = false;
  34434. _this.USELIGHTMAPASSHADOWMAP = false;
  34435. _this.REFLECTIONMAP_3D = false;
  34436. _this.REFLECTIONMAP_SPHERICAL = false;
  34437. _this.REFLECTIONMAP_PLANAR = false;
  34438. _this.REFLECTIONMAP_CUBIC = false;
  34439. _this.REFLECTIONMAP_PROJECTION = false;
  34440. _this.REFLECTIONMAP_SKYBOX = false;
  34441. _this.REFLECTIONMAP_EXPLICIT = false;
  34442. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34443. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34444. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34445. _this.INVERTCUBICMAP = false;
  34446. _this.LOGARITHMICDEPTH = false;
  34447. _this.CAMERATONEMAP = false;
  34448. _this.CAMERACONTRAST = false;
  34449. _this.CAMERACOLORGRADING = false;
  34450. _this.CAMERACOLORCURVES = false;
  34451. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34452. _this.REFRACTION = false;
  34453. _this.REFRACTIONMAP_3D = false;
  34454. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34455. _this.REFRACTIONMAPINLINEARSPACE = false;
  34456. _this.LODBASEDMICROSFURACE = false;
  34457. _this.USEPHYSICALLIGHTFALLOFF = false;
  34458. _this.RADIANCEOVERALPHA = false;
  34459. _this.USEPMREMREFLECTION = false;
  34460. _this.USEPMREMREFRACTION = false;
  34461. _this.INVERTNORMALMAPX = false;
  34462. _this.INVERTNORMALMAPY = false;
  34463. _this.TWOSIDEDLIGHTING = false;
  34464. _this.SHADOWFLOAT = false;
  34465. _this.NORMALXYSCALE = true;
  34466. _this.USERIGHTHANDEDSYSTEM = false;
  34467. _this.METALLICWORKFLOW = false;
  34468. _this.METALLICMAP = false;
  34469. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34470. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34471. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34472. _this.AOSTOREINMETALMAPRED = false;
  34473. _this.MICROSURFACEMAP = false;
  34474. _this.MORPHTARGETS = false;
  34475. _this.MORPHTARGETS_NORMAL = false;
  34476. _this.MORPHTARGETS_TANGENT = false;
  34477. _this.NUM_MORPH_INFLUENCERS = 0;
  34478. _this.ALPHATESTVALUE = 0.4;
  34479. _this.LDROUTPUT = true;
  34480. _this.rebuild();
  34481. return _this;
  34482. }
  34483. PBRMaterialDefines.prototype.reset = function () {
  34484. _super.prototype.reset.call(this);
  34485. this.ALPHATESTVALUE = 0.4;
  34486. this.PBR = true;
  34487. };
  34488. return PBRMaterialDefines;
  34489. }(BABYLON.MaterialDefines));
  34490. /**
  34491. * The Physically based material base class of BJS.
  34492. *
  34493. * This offers the main features of a standard PBR material.
  34494. * For more information, please refer to the documentation :
  34495. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34496. */
  34497. var PBRBaseMaterial = (function (_super) {
  34498. __extends(PBRBaseMaterial, _super);
  34499. /**
  34500. * Instantiates a new PBRMaterial instance.
  34501. *
  34502. * @param name The material name
  34503. * @param scene The scene the material will be use in.
  34504. */
  34505. function PBRBaseMaterial(name, scene) {
  34506. var _this = _super.call(this, name, scene) || this;
  34507. /**
  34508. * Intensity of the direct lights e.g. the four lights available in your scene.
  34509. * This impacts both the direct diffuse and specular highlights.
  34510. */
  34511. _this._directIntensity = 1.0;
  34512. /**
  34513. * Intensity of the emissive part of the material.
  34514. * This helps controlling the emissive effect without modifying the emissive color.
  34515. */
  34516. _this._emissiveIntensity = 1.0;
  34517. /**
  34518. * Intensity of the environment e.g. how much the environment will light the object
  34519. * either through harmonics for rough material or through the refelction for shiny ones.
  34520. */
  34521. _this._environmentIntensity = 1.0;
  34522. /**
  34523. * This is a special control allowing the reduction of the specular highlights coming from the
  34524. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34525. */
  34526. _this._specularIntensity = 1.0;
  34527. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34528. /**
  34529. * Debug Control allowing disabling the bump map on this material.
  34530. */
  34531. _this._disableBumpMap = false;
  34532. /**
  34533. * The camera exposure used on this material.
  34534. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34535. * This corresponds to a photographic exposure.
  34536. */
  34537. _this._cameraExposure = 1.0;
  34538. /**
  34539. * The camera contrast used on this material.
  34540. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  34541. */
  34542. _this._cameraContrast = 1.0;
  34543. /**
  34544. * Color Grading 2D Lookup Texture.
  34545. * This allows special effects like sepia, black and white to sixties rendering style.
  34546. */
  34547. _this._cameraColorGradingTexture = null;
  34548. /**
  34549. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34550. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34551. * 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;
  34552. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34553. */
  34554. _this._cameraColorCurves = null;
  34555. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  34556. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  34557. /**
  34558. * AKA Occlusion Texture Intensity in other nomenclature.
  34559. */
  34560. _this._ambientTextureStrength = 1.0;
  34561. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34562. /**
  34563. * AKA Diffuse Color in other nomenclature.
  34564. */
  34565. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34566. /**
  34567. * AKA Specular Color in other nomenclature.
  34568. */
  34569. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34570. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34571. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34572. /**
  34573. * AKA Glossiness in other nomenclature.
  34574. */
  34575. _this._microSurface = 0.9;
  34576. /**
  34577. * source material index of refraction (IOR)' / 'destination material IOR.
  34578. */
  34579. _this._indexOfRefraction = 0.66;
  34580. /**
  34581. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34582. */
  34583. _this._invertRefractionY = false;
  34584. /**
  34585. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34586. * Materials half opaque for instance using refraction could benefit from this control.
  34587. */
  34588. _this._linkRefractionWithTransparency = false;
  34589. _this._useLightmapAsShadowmap = false;
  34590. /**
  34591. * In this mode, the emissive informtaion will always be added to the lighting once.
  34592. * A light for instance can be thought as emissive.
  34593. */
  34594. _this._useEmissiveAsIllumination = false;
  34595. /**
  34596. * Secifies that the alpha is coming form the albedo channel alpha channel.
  34597. */
  34598. _this._useAlphaFromAlbedoTexture = false;
  34599. /**
  34600. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34601. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34602. */
  34603. _this._useSpecularOverAlpha = true;
  34604. /**
  34605. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34606. */
  34607. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34608. /**
  34609. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34610. */
  34611. _this._useRoughnessFromMetallicTextureAlpha = true;
  34612. /**
  34613. * Specifies if the metallic texture contains the roughness information in its green channel.
  34614. */
  34615. _this._useRoughnessFromMetallicTextureGreen = false;
  34616. /**
  34617. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34618. */
  34619. _this._useMetallnessFromMetallicTextureBlue = false;
  34620. /**
  34621. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34622. */
  34623. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34624. /**
  34625. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34626. */
  34627. _this._useAmbientInGrayScale = false;
  34628. /**
  34629. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34630. * The material will try to infer what glossiness each pixel should be.
  34631. */
  34632. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34633. /**
  34634. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  34635. * the creation of the material.
  34636. */
  34637. _this._useScalarInLinearSpace = false;
  34638. /**
  34639. * BJS is using an harcoded light falloff based on a manually sets up range.
  34640. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34641. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34642. */
  34643. _this._usePhysicalLightFalloff = true;
  34644. /**
  34645. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34646. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34647. */
  34648. _this._useRadianceOverAlpha = true;
  34649. /**
  34650. * Allows using the bump map in parallax mode.
  34651. */
  34652. _this._useParallax = false;
  34653. /**
  34654. * Allows using the bump map in parallax occlusion mode.
  34655. */
  34656. _this._useParallaxOcclusion = false;
  34657. /**
  34658. * Controls the scale bias of the parallax mode.
  34659. */
  34660. _this._parallaxScaleBias = 0.05;
  34661. /**
  34662. * If sets to true, disables all the lights affecting the material.
  34663. */
  34664. _this._disableLighting = false;
  34665. /**
  34666. * Number of Simultaneous lights allowed on the material.
  34667. */
  34668. _this._maxSimultaneousLights = 4;
  34669. /**
  34670. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34671. */
  34672. _this._invertNormalMapX = false;
  34673. /**
  34674. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34675. */
  34676. _this._invertNormalMapY = false;
  34677. /**
  34678. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34679. */
  34680. _this._twoSidedLighting = false;
  34681. /**
  34682. * Defines the alpha limits in alpha test mode.
  34683. */
  34684. _this._alphaCutOff = 0.4;
  34685. /**
  34686. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34687. */
  34688. _this._forceAlphaTest = false;
  34689. /**
  34690. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is useful
  34691. * in combination of post process in float or half float mode.
  34692. */
  34693. _this._ldrOutput = true;
  34694. _this._renderTargets = new BABYLON.SmartArray(16);
  34695. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34696. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34697. _this._tempColor = new BABYLON.Color3();
  34698. _this.getRenderTargetTextures = function () {
  34699. _this._renderTargets.reset();
  34700. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34701. _this._renderTargets.push(_this._reflectionTexture);
  34702. }
  34703. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34704. _this._renderTargets.push(_this._refractionTexture);
  34705. }
  34706. return _this._renderTargets;
  34707. };
  34708. return _this;
  34709. }
  34710. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34711. get: function () {
  34712. return this._useLogarithmicDepth;
  34713. },
  34714. set: function (value) {
  34715. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34716. },
  34717. enumerable: true,
  34718. configurable: true
  34719. });
  34720. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34721. if (this._linkRefractionWithTransparency) {
  34722. return false;
  34723. }
  34724. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34725. };
  34726. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34727. if (this._linkRefractionWithTransparency) {
  34728. return false;
  34729. }
  34730. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34731. };
  34732. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34733. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34734. };
  34735. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34736. return this._albedoTexture;
  34737. };
  34738. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  34739. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  34740. };
  34741. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  34742. if (!useScalarInLinear) {
  34743. color.toLinearSpaceToRef(ref);
  34744. }
  34745. else {
  34746. ref.r = color.r;
  34747. ref.g = color.g;
  34748. ref.b = color.b;
  34749. }
  34750. };
  34751. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  34752. var lightIndex = 0;
  34753. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34754. var light = _a[_i];
  34755. var useUbo = light._uniformBuffer.useUbo;
  34756. var scaledIntensity = light.getScaledIntensity();
  34757. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  34758. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  34759. // GAMMA CORRECTION.
  34760. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  34761. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  34762. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  34763. if (defines["SPECULARTERM"]) {
  34764. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  34765. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  34766. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  34767. }
  34768. // Shadows
  34769. if (scene.shadowsEnabled) {
  34770. BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  34771. }
  34772. light._uniformBuffer.update();
  34773. lightIndex++;
  34774. if (lightIndex === maxSimultaneousLights)
  34775. break;
  34776. }
  34777. };
  34778. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34779. if (this.isFrozen) {
  34780. if (this._wasPreviouslyReady) {
  34781. return true;
  34782. }
  34783. }
  34784. if (!subMesh._materialDefines) {
  34785. subMesh._materialDefines = new PBRMaterialDefines();
  34786. }
  34787. var scene = this.getScene();
  34788. var defines = subMesh._materialDefines;
  34789. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34790. if (defines._renderId === scene.getRenderId()) {
  34791. return true;
  34792. }
  34793. }
  34794. var engine = scene.getEngine();
  34795. // Lights
  34796. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34797. defines._needNormals = true;
  34798. // Textures
  34799. if (defines._areTexturesDirty) {
  34800. defines._needUVs = false;
  34801. if (scene.texturesEnabled) {
  34802. if (scene.getEngine().getCaps().textureLOD) {
  34803. defines.LODBASEDMICROSFURACE = true;
  34804. }
  34805. defines.LDROUTPUT = this._ldrOutput;
  34806. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34807. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34808. return false;
  34809. }
  34810. defines._needUVs = true;
  34811. defines.ALBEDO = true;
  34812. }
  34813. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34814. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34815. return false;
  34816. }
  34817. defines._needUVs = true;
  34818. defines.AMBIENT = true;
  34819. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34820. }
  34821. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34822. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34823. return false;
  34824. }
  34825. defines._needUVs = true;
  34826. defines.OPACITY = true;
  34827. if (this._opacityTexture.getAlphaFromRGB) {
  34828. defines.OPACITYRGB = true;
  34829. }
  34830. }
  34831. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  34832. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34833. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34834. return false;
  34835. }
  34836. defines.REFLECTION = true;
  34837. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34838. defines.INVERTCUBICMAP = true;
  34839. }
  34840. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34841. switch (reflectionTexture.coordinatesMode) {
  34842. case BABYLON.Texture.CUBIC_MODE:
  34843. case BABYLON.Texture.INVCUBIC_MODE:
  34844. defines.REFLECTIONMAP_CUBIC = true;
  34845. break;
  34846. case BABYLON.Texture.EXPLICIT_MODE:
  34847. defines.REFLECTIONMAP_EXPLICIT = true;
  34848. break;
  34849. case BABYLON.Texture.PLANAR_MODE:
  34850. defines.REFLECTIONMAP_PLANAR = true;
  34851. break;
  34852. case BABYLON.Texture.PROJECTION_MODE:
  34853. defines.REFLECTIONMAP_PROJECTION = true;
  34854. break;
  34855. case BABYLON.Texture.SKYBOX_MODE:
  34856. defines.REFLECTIONMAP_SKYBOX = true;
  34857. break;
  34858. case BABYLON.Texture.SPHERICAL_MODE:
  34859. defines.REFLECTIONMAP_SPHERICAL = true;
  34860. break;
  34861. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34862. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  34863. break;
  34864. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34865. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  34866. break;
  34867. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34868. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  34869. break;
  34870. }
  34871. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  34872. defines.USESPHERICALFROMREFLECTIONMAP = true;
  34873. if (reflectionTexture.isPMREM) {
  34874. defines.USEPMREMREFLECTION = true;
  34875. }
  34876. }
  34877. }
  34878. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34879. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34880. return false;
  34881. }
  34882. defines._needUVs = true;
  34883. defines.LIGHTMAP = true;
  34884. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34885. }
  34886. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34887. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34888. return false;
  34889. }
  34890. defines._needUVs = true;
  34891. defines.EMISSIVE = true;
  34892. }
  34893. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34894. if (this._metallicTexture) {
  34895. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  34896. return false;
  34897. }
  34898. defines._needUVs = true;
  34899. defines.METALLICWORKFLOW = true;
  34900. defines.METALLICMAP = true;
  34901. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  34902. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  34903. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  34904. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  34905. }
  34906. else if (this._reflectivityTexture) {
  34907. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  34908. return false;
  34909. }
  34910. defines._needUVs = true;
  34911. defines.REFLECTIVITY = true;
  34912. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  34913. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  34914. }
  34915. if (this._microSurfaceTexture) {
  34916. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  34917. return false;
  34918. }
  34919. defines._needUVs = true;
  34920. defines.MICROSURFACEMAP = true;
  34921. }
  34922. }
  34923. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34924. // Bump texure can not be none blocking.
  34925. if (!this._bumpTexture.isReady()) {
  34926. return false;
  34927. }
  34928. defines._needUVs = true;
  34929. defines.BUMP = true;
  34930. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34931. defines.PARALLAX = true;
  34932. if (this._useParallaxOcclusion) {
  34933. defines.PARALLAXOCCLUSION = true;
  34934. }
  34935. }
  34936. if (this._invertNormalMapX) {
  34937. defines.INVERTNORMALMAPX = true;
  34938. }
  34939. if (this._invertNormalMapY) {
  34940. defines.INVERTNORMALMAPY = true;
  34941. }
  34942. if (scene._mirroredCameraPosition) {
  34943. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  34944. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  34945. }
  34946. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  34947. }
  34948. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34949. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34950. return false;
  34951. }
  34952. defines._needUVs = true;
  34953. defines.REFRACTION = true;
  34954. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34955. if (this._linkRefractionWithTransparency) {
  34956. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  34957. }
  34958. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  34959. defines.REFRACTIONMAPINLINEARSPACE = true;
  34960. if (this._refractionTexture.isPMREM) {
  34961. defines.USEPMREMREFRACTION = true;
  34962. }
  34963. }
  34964. }
  34965. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  34966. // Color Grading texure can not be none blocking.
  34967. if (!this._cameraColorGradingTexture.isReady()) {
  34968. return false;
  34969. }
  34970. defines.CAMERACOLORGRADING = true;
  34971. }
  34972. if (!this.backFaceCulling && this._twoSidedLighting) {
  34973. defines.TWOSIDEDLIGHTING = true;
  34974. }
  34975. if (this._shouldUseAlphaFromAlbedoTexture()) {
  34976. defines.ALPHAFROMALBEDO = true;
  34977. }
  34978. if (this._useEmissiveAsIllumination) {
  34979. defines.EMISSIVEASILLUMINATION = true;
  34980. }
  34981. if (this._cameraContrast != 1) {
  34982. defines.CAMERACONTRAST = true;
  34983. }
  34984. if (this._cameraExposure != 1) {
  34985. defines.CAMERATONEMAP = true;
  34986. }
  34987. if (this._cameraColorCurves) {
  34988. defines.CAMERACOLORCURVES = true;
  34989. }
  34990. if (this._useSpecularOverAlpha) {
  34991. defines.SPECULAROVERALPHA = true;
  34992. }
  34993. if (this._usePhysicalLightFalloff) {
  34994. defines.USEPHYSICALLIGHTFALLOFF = true;
  34995. }
  34996. if (this._useRadianceOverAlpha) {
  34997. defines.RADIANCEOVERALPHA = true;
  34998. }
  34999. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35000. defines.METALLICWORKFLOW = true;
  35001. }
  35002. defines.ALPHATESTVALUE = this._alphaCutOff;
  35003. }
  35004. }
  35005. if (defines._areFresnelDirty) {
  35006. if (BABYLON.StandardMaterial.FresnelEnabled) {
  35007. // Fresnel
  35008. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  35009. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  35010. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  35011. defines.OPACITYFRESNEL = true;
  35012. }
  35013. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  35014. defines.EMISSIVEFRESNEL = true;
  35015. }
  35016. defines.FRESNEL = true;
  35017. }
  35018. }
  35019. }
  35020. // Misc.
  35021. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35022. // Values that need to be evaluated on every frame
  35023. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  35024. // Attribs
  35025. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35026. if (mesh) {
  35027. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35028. mesh.createNormals(true);
  35029. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35030. }
  35031. }
  35032. }
  35033. // Get correct effect
  35034. if (defines.isDirty) {
  35035. defines.markAsProcessed();
  35036. scene.resetCachedMaterial();
  35037. // Fallbacks
  35038. var fallbacks = new BABYLON.EffectFallbacks();
  35039. if (defines.REFLECTION) {
  35040. fallbacks.addFallback(0, "REFLECTION");
  35041. }
  35042. if (defines.REFRACTION) {
  35043. fallbacks.addFallback(0, "REFRACTION");
  35044. }
  35045. if (defines.REFLECTIVITY) {
  35046. fallbacks.addFallback(0, "REFLECTIVITY");
  35047. }
  35048. if (defines.BUMP) {
  35049. fallbacks.addFallback(0, "BUMP");
  35050. }
  35051. if (defines.PARALLAX) {
  35052. fallbacks.addFallback(1, "PARALLAX");
  35053. }
  35054. if (defines.PARALLAXOCCLUSION) {
  35055. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35056. }
  35057. if (defines.SPECULAROVERALPHA) {
  35058. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35059. }
  35060. if (defines.FOG) {
  35061. fallbacks.addFallback(1, "FOG");
  35062. }
  35063. if (defines.POINTSIZE) {
  35064. fallbacks.addFallback(0, "POINTSIZE");
  35065. }
  35066. if (defines.LOGARITHMICDEPTH) {
  35067. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35068. }
  35069. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35070. if (defines.SPECULARTERM) {
  35071. fallbacks.addFallback(0, "SPECULARTERM");
  35072. }
  35073. if (defines.OPACITYFRESNEL) {
  35074. fallbacks.addFallback(1, "OPACITYFRESNEL");
  35075. }
  35076. if (defines.EMISSIVEFRESNEL) {
  35077. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  35078. }
  35079. if (defines.FRESNEL) {
  35080. fallbacks.addFallback(3, "FRESNEL");
  35081. }
  35082. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35083. fallbacks.addCPUSkinningFallback(0, mesh);
  35084. }
  35085. //Attributes
  35086. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35087. if (defines.NORMAL) {
  35088. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35089. }
  35090. if (defines.TANGENT) {
  35091. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35092. }
  35093. if (defines.UV1) {
  35094. attribs.push(BABYLON.VertexBuffer.UVKind);
  35095. }
  35096. if (defines.UV2) {
  35097. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35098. }
  35099. if (defines.VERTEXCOLOR) {
  35100. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35101. }
  35102. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35103. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35104. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35105. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35106. "vFogInfos", "vFogColor", "pointSize",
  35107. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35108. "mBones",
  35109. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35110. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  35111. "vLightingIntensity",
  35112. "logarithmicDepthConstant",
  35113. "vSphericalX", "vSphericalY", "vSphericalZ",
  35114. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35115. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35116. "vMicrosurfaceTextureLods",
  35117. "vCameraInfos"
  35118. ];
  35119. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35120. var uniformBuffers = ["Material", "Scene"];
  35121. if (defines.CAMERACOLORCURVES) {
  35122. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35123. }
  35124. if (defines.CAMERACOLORGRADING) {
  35125. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  35126. }
  35127. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35128. uniformsNames: uniforms,
  35129. uniformBuffersNames: uniformBuffers,
  35130. samplers: samplers,
  35131. defines: defines,
  35132. maxSimultaneousLights: this._maxSimultaneousLights
  35133. });
  35134. var onCompiled = function (effect) {
  35135. if (this.onCompiled) {
  35136. this.onCompiled(effect);
  35137. }
  35138. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35139. }.bind(this);
  35140. var join = defines.toString();
  35141. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35142. attributes: attribs,
  35143. uniformsNames: uniforms,
  35144. uniformBuffersNames: uniformBuffers,
  35145. samplers: samplers,
  35146. defines: join,
  35147. fallbacks: fallbacks,
  35148. onCompiled: onCompiled,
  35149. onError: this.onError,
  35150. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35151. }, engine), defines);
  35152. this.buildUniformLayout();
  35153. }
  35154. if (!subMesh.effect.isReady()) {
  35155. return false;
  35156. }
  35157. defines._renderId = scene.getRenderId();
  35158. this._wasPreviouslyReady = true;
  35159. return true;
  35160. };
  35161. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35162. // Order is important !
  35163. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35164. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35165. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35166. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35167. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35168. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35169. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35170. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35171. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35172. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35173. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35174. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35175. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35176. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35177. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35178. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35179. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35180. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35181. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35182. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35183. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35184. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35185. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35186. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  35187. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35188. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35189. this._uniformBuffer.addUniform("opacityParts", 4);
  35190. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35191. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35192. this._uniformBuffer.addUniform("pointSize", 1);
  35193. this._uniformBuffer.create();
  35194. };
  35195. PBRBaseMaterial.prototype.unbind = function () {
  35196. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35197. this._uniformBuffer.setTexture("reflection2DSampler", null);
  35198. }
  35199. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35200. this._uniformBuffer.setTexture("refraction2DSampler", null);
  35201. }
  35202. _super.prototype.unbind.call(this);
  35203. };
  35204. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35205. this._activeEffect.setMatrix("world", world);
  35206. };
  35207. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35208. var scene = this.getScene();
  35209. var defines = subMesh._materialDefines;
  35210. if (!defines) {
  35211. return;
  35212. }
  35213. var effect = subMesh.effect;
  35214. this._activeEffect = effect;
  35215. // Matrices
  35216. this.bindOnlyWorldMatrix(world);
  35217. // Bones
  35218. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35219. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35220. this._uniformBuffer.bindToEffect(effect, "Material");
  35221. this.bindViewProjection(effect);
  35222. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35223. // Fresnel
  35224. if (BABYLON.StandardMaterial.FresnelEnabled) {
  35225. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  35226. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  35227. }
  35228. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  35229. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  35230. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  35231. }
  35232. }
  35233. // Texture uniforms
  35234. if (scene.texturesEnabled) {
  35235. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35236. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35237. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  35238. }
  35239. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35240. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35241. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35242. }
  35243. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35244. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35245. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35246. }
  35247. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  35248. ;
  35249. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35250. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  35251. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35252. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35253. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35254. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  35255. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  35256. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  35257. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  35258. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  35259. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  35260. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  35261. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  35262. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  35263. }
  35264. }
  35265. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35266. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35267. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35268. }
  35269. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35270. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35271. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35272. }
  35273. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35274. if (this._metallicTexture) {
  35275. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35276. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  35277. }
  35278. else if (this._reflectivityTexture) {
  35279. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35280. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  35281. }
  35282. if (this._microSurfaceTexture) {
  35283. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35284. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  35285. }
  35286. }
  35287. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35288. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35289. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35290. }
  35291. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35292. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  35293. var depth = 1.0;
  35294. if (!this._refractionTexture.isCube) {
  35295. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35296. if (this._refractionTexture.depth) {
  35297. depth = this._refractionTexture.depth;
  35298. }
  35299. }
  35300. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35301. }
  35302. if ((reflectionTexture || this._refractionTexture)) {
  35303. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  35304. }
  35305. }
  35306. // Point size
  35307. if (this.pointsCloud) {
  35308. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35309. }
  35310. // Colors
  35311. if (defines.METALLICWORKFLOW) {
  35312. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35313. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35314. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35315. }
  35316. else {
  35317. // GAMMA CORRECTION.
  35318. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  35319. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  35320. }
  35321. // GAMMA CORRECTION.
  35322. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  35323. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  35324. // GAMMA CORRECTION.
  35325. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  35326. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  35327. // GAMMA CORRECTION.
  35328. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  35329. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  35330. // Misc
  35331. this._lightingInfos.x = this._directIntensity;
  35332. this._lightingInfos.y = this._emissiveIntensity;
  35333. this._lightingInfos.z = this._environmentIntensity;
  35334. this._lightingInfos.w = this._specularIntensity;
  35335. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35336. }
  35337. // Textures
  35338. if (scene.texturesEnabled) {
  35339. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35340. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35341. }
  35342. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35343. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35344. }
  35345. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35346. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35347. }
  35348. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35349. if (reflectionTexture.isCube) {
  35350. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  35351. }
  35352. else {
  35353. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  35354. }
  35355. }
  35356. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35357. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35358. }
  35359. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35360. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35361. }
  35362. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35363. if (this._metallicTexture) {
  35364. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35365. }
  35366. else if (this._reflectivityTexture) {
  35367. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35368. }
  35369. if (this._microSurfaceTexture) {
  35370. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35371. }
  35372. }
  35373. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35374. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35375. }
  35376. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35377. if (this._refractionTexture.isCube) {
  35378. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  35379. }
  35380. else {
  35381. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  35382. }
  35383. }
  35384. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  35385. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._activeEffect);
  35386. }
  35387. }
  35388. // Clip plane
  35389. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35390. // Colors
  35391. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35392. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35393. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35394. }
  35395. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35396. // Lights
  35397. if (scene.lightsEnabled && !this._disableLighting) {
  35398. BABYLON.PBRMaterial.BindLights(scene, mesh, this._activeEffect, defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35399. }
  35400. // View
  35401. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35402. this.bindView(effect);
  35403. }
  35404. // Fog
  35405. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35406. // Morph targets
  35407. if (defines.NUM_MORPH_INFLUENCERS) {
  35408. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35409. }
  35410. this._cameraInfos.x = this._cameraExposure;
  35411. this._cameraInfos.y = this._cameraContrast;
  35412. effect.setVector4("vCameraInfos", this._cameraInfos);
  35413. if (this._cameraColorCurves) {
  35414. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._activeEffect);
  35415. }
  35416. // Log. depth
  35417. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35418. }
  35419. this._uniformBuffer.update();
  35420. this._afterBind(mesh);
  35421. scene = null;
  35422. };
  35423. PBRBaseMaterial.prototype.getAnimatables = function () {
  35424. var results = [];
  35425. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35426. results.push(this._albedoTexture);
  35427. }
  35428. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35429. results.push(this._ambientTexture);
  35430. }
  35431. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35432. results.push(this._opacityTexture);
  35433. }
  35434. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35435. results.push(this._reflectionTexture);
  35436. }
  35437. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35438. results.push(this._emissiveTexture);
  35439. }
  35440. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35441. results.push(this._metallicTexture);
  35442. }
  35443. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35444. results.push(this._reflectivityTexture);
  35445. }
  35446. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35447. results.push(this._bumpTexture);
  35448. }
  35449. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35450. results.push(this._lightmapTexture);
  35451. }
  35452. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35453. results.push(this._refractionTexture);
  35454. }
  35455. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  35456. results.push(this._cameraColorGradingTexture);
  35457. }
  35458. return results;
  35459. };
  35460. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35461. if (forceDisposeTextures) {
  35462. if (this._albedoTexture) {
  35463. this._albedoTexture.dispose();
  35464. }
  35465. if (this._ambientTexture) {
  35466. this._ambientTexture.dispose();
  35467. }
  35468. if (this._opacityTexture) {
  35469. this._opacityTexture.dispose();
  35470. }
  35471. if (this._reflectionTexture) {
  35472. this._reflectionTexture.dispose();
  35473. }
  35474. if (this._emissiveTexture) {
  35475. this._emissiveTexture.dispose();
  35476. }
  35477. if (this._metallicTexture) {
  35478. this._metallicTexture.dispose();
  35479. }
  35480. if (this._reflectivityTexture) {
  35481. this._reflectivityTexture.dispose();
  35482. }
  35483. if (this._bumpTexture) {
  35484. this._bumpTexture.dispose();
  35485. }
  35486. if (this._lightmapTexture) {
  35487. this._lightmapTexture.dispose();
  35488. }
  35489. if (this._refractionTexture) {
  35490. this._refractionTexture.dispose();
  35491. }
  35492. if (this._cameraColorGradingTexture) {
  35493. this._cameraColorGradingTexture.dispose();
  35494. }
  35495. }
  35496. this._renderTargets.dispose();
  35497. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35498. };
  35499. return PBRBaseMaterial;
  35500. }(BABYLON.PushMaterial));
  35501. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  35502. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35503. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  35504. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  35505. __decorate([
  35506. BABYLON.serialize()
  35507. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35508. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35509. })(BABYLON || (BABYLON = {}));
  35510. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35511. var BABYLON;
  35512. (function (BABYLON) {
  35513. var Internals;
  35514. (function (Internals) {
  35515. /**
  35516. * The Physically based simple base material of BJS.
  35517. *
  35518. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35519. * It is used as the base class for both the specGloss and metalRough conventions.
  35520. */
  35521. var PBRBaseSimpleMaterial = (function (_super) {
  35522. __extends(PBRBaseSimpleMaterial, _super);
  35523. /**
  35524. * Instantiates a new PBRMaterial instance.
  35525. *
  35526. * @param name The material name
  35527. * @param scene The scene the material will be use in.
  35528. */
  35529. function PBRBaseSimpleMaterial(name, scene) {
  35530. var _this = _super.call(this, name, scene) || this;
  35531. /**
  35532. * Number of Simultaneous lights allowed on the material.
  35533. */
  35534. _this.maxSimultaneousLights = 4;
  35535. /**
  35536. * If sets to true, disables all the lights affecting the material.
  35537. */
  35538. _this.disableLighting = false;
  35539. /**
  35540. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35541. */
  35542. _this.invertNormalMapX = false;
  35543. /**
  35544. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35545. */
  35546. _this.invertNormalMapY = false;
  35547. /**
  35548. * Emissivie color used to self-illuminate the model.
  35549. */
  35550. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35551. /**
  35552. * Occlusion Channel Strenght.
  35553. */
  35554. _this.occlusionStrength = 1.0;
  35555. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35556. _this._useEmissiveAsIllumination = true;
  35557. _this._useAmbientInGrayScale = true;
  35558. _this._useScalarInLinearSpace = true;
  35559. return _this;
  35560. }
  35561. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35562. /**
  35563. * Gets the current transparency mode.
  35564. */
  35565. get: function () {
  35566. return this._transparencyMode;
  35567. },
  35568. /**
  35569. * Sets the transparency mode of the material.
  35570. */
  35571. set: function (value) {
  35572. if (this._transparencyMode === value) {
  35573. return;
  35574. }
  35575. this._transparencyMode = value;
  35576. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35577. this._forceAlphaTest = true;
  35578. }
  35579. else {
  35580. this._forceAlphaTest = false;
  35581. }
  35582. this._markAllSubMeshesAsTexturesDirty();
  35583. },
  35584. enumerable: true,
  35585. configurable: true
  35586. });
  35587. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35588. /**
  35589. * Gets the current double sided mode.
  35590. */
  35591. get: function () {
  35592. return this._twoSidedLighting;
  35593. },
  35594. /**
  35595. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35596. */
  35597. set: function (value) {
  35598. if (this._twoSidedLighting === value) {
  35599. return;
  35600. }
  35601. this._twoSidedLighting = value;
  35602. this.backFaceCulling = !value;
  35603. this._markAllSubMeshesAsTexturesDirty();
  35604. },
  35605. enumerable: true,
  35606. configurable: true
  35607. });
  35608. /**
  35609. * Specifies wether or not the alpha value of the albedo texture should be used.
  35610. */
  35611. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35612. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35613. };
  35614. /**
  35615. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35616. */
  35617. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35618. if (this._linkRefractionWithTransparency) {
  35619. return false;
  35620. }
  35621. return (this.alpha < 1.0) ||
  35622. (this._shouldUseAlphaFromAlbedoTexture() &&
  35623. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35624. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35625. };
  35626. /**
  35627. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35628. */
  35629. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35630. if (this._linkRefractionWithTransparency) {
  35631. return false;
  35632. }
  35633. return this._shouldUseAlphaFromAlbedoTexture() &&
  35634. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35635. };
  35636. return PBRBaseSimpleMaterial;
  35637. }(BABYLON.PBRBaseMaterial));
  35638. __decorate([
  35639. BABYLON.serialize(),
  35640. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35641. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35642. __decorate([
  35643. BABYLON.serialize(),
  35644. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35645. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35646. __decorate([
  35647. BABYLON.serializeAsTexture(),
  35648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35649. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35650. __decorate([
  35651. BABYLON.serialize(),
  35652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35653. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35654. __decorate([
  35655. BABYLON.serialize(),
  35656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35657. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35658. __decorate([
  35659. BABYLON.serializeAsTexture(),
  35660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35661. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35662. __decorate([
  35663. BABYLON.serializeAsColor3("emissive"),
  35664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35665. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35666. __decorate([
  35667. BABYLON.serializeAsTexture(),
  35668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35669. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35670. __decorate([
  35671. BABYLON.serialize(),
  35672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35673. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35674. __decorate([
  35675. BABYLON.serializeAsTexture(),
  35676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35677. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35678. __decorate([
  35679. BABYLON.serialize(),
  35680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35681. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35682. __decorate([
  35683. BABYLON.serialize()
  35684. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35685. __decorate([
  35686. BABYLON.serialize()
  35687. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35688. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35689. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35690. })(BABYLON || (BABYLON = {}));
  35691. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35692. var BABYLON;
  35693. (function (BABYLON) {
  35694. /**
  35695. * The Physically based material of BJS.
  35696. *
  35697. * This offers the main features of a standard PBR material.
  35698. * For more information, please refer to the documentation :
  35699. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35700. */
  35701. var PBRMaterial = (function (_super) {
  35702. __extends(PBRMaterial, _super);
  35703. /**
  35704. * Instantiates a new PBRMaterial instance.
  35705. *
  35706. * @param name The material name
  35707. * @param scene The scene the material will be use in.
  35708. */
  35709. function PBRMaterial(name, scene) {
  35710. var _this = _super.call(this, name, scene) || this;
  35711. /**
  35712. * Intensity of the direct lights e.g. the four lights available in your scene.
  35713. * This impacts both the direct diffuse and specular highlights.
  35714. */
  35715. _this.directIntensity = 1.0;
  35716. /**
  35717. * Intensity of the emissive part of the material.
  35718. * This helps controlling the emissive effect without modifying the emissive color.
  35719. */
  35720. _this.emissiveIntensity = 1.0;
  35721. /**
  35722. * Intensity of the environment e.g. how much the environment will light the object
  35723. * either through harmonics for rough material or through the refelction for shiny ones.
  35724. */
  35725. _this.environmentIntensity = 1.0;
  35726. /**
  35727. * This is a special control allowing the reduction of the specular highlights coming from the
  35728. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35729. */
  35730. _this.specularIntensity = 1.0;
  35731. /**
  35732. * Debug Control allowing disabling the bump map on this material.
  35733. */
  35734. _this.disableBumpMap = false;
  35735. /**
  35736. * The camera exposure used on this material.
  35737. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35738. * This corresponds to a photographic exposure.
  35739. */
  35740. _this.cameraExposure = 1.0;
  35741. /**
  35742. * The camera contrast used on this material.
  35743. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  35744. */
  35745. _this.cameraContrast = 1.0;
  35746. /**
  35747. * Color Grading 2D Lookup Texture.
  35748. * This allows special effects like sepia, black and white to sixties rendering style.
  35749. */
  35750. _this.cameraColorGradingTexture = null;
  35751. /**
  35752. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35753. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35754. * 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;
  35755. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35756. */
  35757. _this.cameraColorCurves = null;
  35758. /**
  35759. * AKA Occlusion Texture Intensity in other nomenclature.
  35760. */
  35761. _this.ambientTextureStrength = 1.0;
  35762. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35763. /**
  35764. * AKA Diffuse Color in other nomenclature.
  35765. */
  35766. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35767. /**
  35768. * AKA Specular Color in other nomenclature.
  35769. */
  35770. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35771. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35772. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35773. /**
  35774. * AKA Glossiness in other nomenclature.
  35775. */
  35776. _this.microSurface = 0.9;
  35777. /**
  35778. * source material index of refraction (IOR)' / 'destination material IOR.
  35779. */
  35780. _this.indexOfRefraction = 0.66;
  35781. /**
  35782. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35783. */
  35784. _this.invertRefractionY = false;
  35785. /**
  35786. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35787. * Materials half opaque for instance using refraction could benefit from this control.
  35788. */
  35789. _this.linkRefractionWithTransparency = false;
  35790. _this.useLightmapAsShadowmap = false;
  35791. /**
  35792. * In this mode, the emissive informtaion will always be added to the lighting once.
  35793. * A light for instance can be thought as emissive.
  35794. */
  35795. _this.useEmissiveAsIllumination = false;
  35796. /**
  35797. * Secifies that the alpha is coming form the albedo channel alpha channel.
  35798. */
  35799. _this.useAlphaFromAlbedoTexture = false;
  35800. /**
  35801. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35802. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35803. */
  35804. _this.useSpecularOverAlpha = true;
  35805. /**
  35806. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35807. */
  35808. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35809. /**
  35810. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35811. */
  35812. _this.useRoughnessFromMetallicTextureAlpha = true;
  35813. /**
  35814. * Specifies if the metallic texture contains the roughness information in its green channel.
  35815. */
  35816. _this.useRoughnessFromMetallicTextureGreen = false;
  35817. /**
  35818. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35819. */
  35820. _this.useMetallnessFromMetallicTextureBlue = false;
  35821. /**
  35822. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35823. */
  35824. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35825. /**
  35826. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35827. */
  35828. _this.useAmbientInGrayScale = false;
  35829. /**
  35830. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35831. * The material will try to infer what glossiness each pixel should be.
  35832. */
  35833. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35834. /**
  35835. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  35836. * the creation of the material.
  35837. */
  35838. _this.useScalarInLinearSpace = false;
  35839. /**
  35840. * BJS is using an harcoded light falloff based on a manually sets up range.
  35841. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35842. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35843. */
  35844. _this.usePhysicalLightFalloff = true;
  35845. /**
  35846. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35847. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35848. */
  35849. _this.useRadianceOverAlpha = true;
  35850. /**
  35851. * Allows using the bump map in parallax mode.
  35852. */
  35853. _this.useParallax = false;
  35854. /**
  35855. * Allows using the bump map in parallax occlusion mode.
  35856. */
  35857. _this.useParallaxOcclusion = false;
  35858. /**
  35859. * Controls the scale bias of the parallax mode.
  35860. */
  35861. _this.parallaxScaleBias = 0.05;
  35862. /**
  35863. * If sets to true, disables all the lights affecting the material.
  35864. */
  35865. _this.disableLighting = false;
  35866. /**
  35867. * Number of Simultaneous lights allowed on the material.
  35868. */
  35869. _this.maxSimultaneousLights = 4;
  35870. /**
  35871. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35872. */
  35873. _this.invertNormalMapX = false;
  35874. /**
  35875. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35876. */
  35877. _this.invertNormalMapY = false;
  35878. /**
  35879. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35880. */
  35881. _this.twoSidedLighting = false;
  35882. return _this;
  35883. }
  35884. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35885. /**
  35886. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35887. */
  35888. get: function () {
  35889. return this._PBRMATERIAL_OPAQUE;
  35890. },
  35891. enumerable: true,
  35892. configurable: true
  35893. });
  35894. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35895. /**
  35896. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35897. */
  35898. get: function () {
  35899. return this._PBRMATERIAL_ALPHATEST;
  35900. },
  35901. enumerable: true,
  35902. configurable: true
  35903. });
  35904. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35905. /**
  35906. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35907. */
  35908. get: function () {
  35909. return this._PBRMATERIAL_ALPHABLEND;
  35910. },
  35911. enumerable: true,
  35912. configurable: true
  35913. });
  35914. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35915. /**
  35916. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35917. * They are also discarded below the alpha cutoff threshold to improve performances.
  35918. */
  35919. get: function () {
  35920. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35921. },
  35922. enumerable: true,
  35923. configurable: true
  35924. });
  35925. PBRMaterial.prototype.getClassName = function () {
  35926. return "PBRMaterial";
  35927. };
  35928. PBRMaterial.prototype.clone = function (name) {
  35929. var _this = this;
  35930. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  35931. };
  35932. PBRMaterial.prototype.serialize = function () {
  35933. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35934. serializationObject.customType = "BABYLON.PBRMaterial";
  35935. return serializationObject;
  35936. };
  35937. // Statics
  35938. PBRMaterial.Parse = function (source, scene, rootUrl) {
  35939. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  35940. };
  35941. return PBRMaterial;
  35942. }(BABYLON.PBRBaseMaterial));
  35943. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  35944. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  35945. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  35946. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  35947. __decorate([
  35948. BABYLON.serialize(),
  35949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35950. ], PBRMaterial.prototype, "directIntensity", void 0);
  35951. __decorate([
  35952. BABYLON.serialize(),
  35953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35954. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  35955. __decorate([
  35956. BABYLON.serialize(),
  35957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35958. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  35959. __decorate([
  35960. BABYLON.serialize(),
  35961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35962. ], PBRMaterial.prototype, "specularIntensity", void 0);
  35963. __decorate([
  35964. BABYLON.serialize(),
  35965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35966. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  35967. __decorate([
  35968. BABYLON.serialize(),
  35969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35970. ], PBRMaterial.prototype, "cameraExposure", void 0);
  35971. __decorate([
  35972. BABYLON.serialize(),
  35973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35974. ], PBRMaterial.prototype, "cameraContrast", void 0);
  35975. __decorate([
  35976. BABYLON.serializeAsTexture(),
  35977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35978. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  35979. __decorate([
  35980. BABYLON.serializeAsColorCurves(),
  35981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35982. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  35983. __decorate([
  35984. BABYLON.serializeAsTexture(),
  35985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35986. ], PBRMaterial.prototype, "albedoTexture", void 0);
  35987. __decorate([
  35988. BABYLON.serializeAsTexture(),
  35989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35990. ], PBRMaterial.prototype, "ambientTexture", void 0);
  35991. __decorate([
  35992. BABYLON.serialize(),
  35993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35994. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  35995. __decorate([
  35996. BABYLON.serializeAsTexture(),
  35997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35998. ], PBRMaterial.prototype, "opacityTexture", void 0);
  35999. __decorate([
  36000. BABYLON.serializeAsTexture(),
  36001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36002. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36003. __decorate([
  36004. BABYLON.serializeAsTexture(),
  36005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36006. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36007. __decorate([
  36008. BABYLON.serializeAsTexture(),
  36009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36010. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36011. __decorate([
  36012. BABYLON.serializeAsTexture(),
  36013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36014. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36015. __decorate([
  36016. BABYLON.serialize(),
  36017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36018. ], PBRMaterial.prototype, "metallic", void 0);
  36019. __decorate([
  36020. BABYLON.serialize(),
  36021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36022. ], PBRMaterial.prototype, "roughness", void 0);
  36023. __decorate([
  36024. BABYLON.serializeAsTexture(),
  36025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36026. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36027. __decorate([
  36028. BABYLON.serializeAsTexture(),
  36029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36030. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36031. __decorate([
  36032. BABYLON.serializeAsTexture(),
  36033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36034. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36035. __decorate([
  36036. BABYLON.serializeAsTexture(),
  36037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36038. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36039. __decorate([
  36040. BABYLON.serializeAsColor3("ambient"),
  36041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36042. ], PBRMaterial.prototype, "ambientColor", void 0);
  36043. __decorate([
  36044. BABYLON.serializeAsColor3("albedo"),
  36045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36046. ], PBRMaterial.prototype, "albedoColor", void 0);
  36047. __decorate([
  36048. BABYLON.serializeAsColor3("reflectivity"),
  36049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36050. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36051. __decorate([
  36052. BABYLON.serializeAsColor3("reflection"),
  36053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36054. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36055. __decorate([
  36056. BABYLON.serializeAsColor3("emissive"),
  36057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36058. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36059. __decorate([
  36060. BABYLON.serialize(),
  36061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36062. ], PBRMaterial.prototype, "microSurface", void 0);
  36063. __decorate([
  36064. BABYLON.serialize(),
  36065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36066. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36067. __decorate([
  36068. BABYLON.serialize(),
  36069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36070. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36071. __decorate([
  36072. BABYLON.serializeAsFresnelParameters(),
  36073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36074. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  36075. __decorate([
  36076. BABYLON.serializeAsFresnelParameters(),
  36077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36078. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  36079. __decorate([
  36080. BABYLON.serialize(),
  36081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36082. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36083. __decorate([
  36084. BABYLON.serialize(),
  36085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36086. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36087. __decorate([
  36088. BABYLON.serialize(),
  36089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36090. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36091. __decorate([
  36092. BABYLON.serialize(),
  36093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36094. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36095. __decorate([
  36096. BABYLON.serialize(),
  36097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36098. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36099. __decorate([
  36100. BABYLON.serialize(),
  36101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36102. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36103. __decorate([
  36104. BABYLON.serialize(),
  36105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36106. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36107. __decorate([
  36108. BABYLON.serialize(),
  36109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36110. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36111. __decorate([
  36112. BABYLON.serialize(),
  36113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36114. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36115. __decorate([
  36116. BABYLON.serialize(),
  36117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36118. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36119. __decorate([
  36120. BABYLON.serialize(),
  36121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36122. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36123. __decorate([
  36124. BABYLON.serialize(),
  36125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36126. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36127. __decorate([
  36128. BABYLON.serialize(),
  36129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36130. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  36131. __decorate([
  36132. BABYLON.serialize(),
  36133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36134. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36135. __decorate([
  36136. BABYLON.serialize(),
  36137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36138. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36139. __decorate([
  36140. BABYLON.serialize(),
  36141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36142. ], PBRMaterial.prototype, "useParallax", void 0);
  36143. __decorate([
  36144. BABYLON.serialize(),
  36145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36146. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36147. __decorate([
  36148. BABYLON.serialize(),
  36149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36150. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36151. __decorate([
  36152. BABYLON.serialize(),
  36153. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36154. ], PBRMaterial.prototype, "disableLighting", void 0);
  36155. __decorate([
  36156. BABYLON.serialize(),
  36157. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36158. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36159. __decorate([
  36160. BABYLON.serialize(),
  36161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36162. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36163. __decorate([
  36164. BABYLON.serialize(),
  36165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36166. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36167. __decorate([
  36168. BABYLON.serialize(),
  36169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36170. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36171. BABYLON.PBRMaterial = PBRMaterial;
  36172. })(BABYLON || (BABYLON = {}));
  36173. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36174. var BABYLON;
  36175. (function (BABYLON) {
  36176. /**
  36177. * The PBR material of BJS following the metal roughness convention.
  36178. *
  36179. * This fits to the define PBR convention in the GLTF definition:
  36180. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36181. */
  36182. var PBRMetallicRoughnessMaterial = (function (_super) {
  36183. __extends(PBRMetallicRoughnessMaterial, _super);
  36184. /**
  36185. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36186. *
  36187. * @param name The material name
  36188. * @param scene The scene the material will be use in.
  36189. */
  36190. function PBRMetallicRoughnessMaterial(name, scene) {
  36191. var _this = _super.call(this, name, scene) || this;
  36192. _this._useRoughnessFromMetallicTextureGreen = true;
  36193. _this._useMetallnessFromMetallicTextureBlue = true;
  36194. return _this;
  36195. }
  36196. /**
  36197. * Return the currrent class name of the material.
  36198. */
  36199. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36200. return "PBRMetallicRoughnessMaterial";
  36201. };
  36202. /**
  36203. * Serialize the material to a parsable JSON object.
  36204. */
  36205. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36206. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36207. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36208. return serializationObject;
  36209. };
  36210. /**
  36211. * Parses a JSON object correponding to the serialize function.
  36212. */
  36213. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36214. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36215. };
  36216. return PBRMetallicRoughnessMaterial;
  36217. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36218. __decorate([
  36219. BABYLON.serializeAsTexture(),
  36220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36221. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36222. __decorate([
  36223. BABYLON.serializeAsTexture(),
  36224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36225. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36226. __decorate([
  36227. BABYLON.serialize(),
  36228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36229. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36230. __decorate([
  36231. BABYLON.serialize(),
  36232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36233. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36234. __decorate([
  36235. BABYLON.serializeAsTexture(),
  36236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36237. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36238. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36239. })(BABYLON || (BABYLON = {}));
  36240. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36241. var BABYLON;
  36242. (function (BABYLON) {
  36243. /**
  36244. * The PBR material of BJS following the specular glossiness convention.
  36245. *
  36246. * This fits to the define PBR convention in the GLTF definition:
  36247. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36248. */
  36249. var PBRSpecularGlossinessMaterial = (function (_super) {
  36250. __extends(PBRSpecularGlossinessMaterial, _super);
  36251. /**
  36252. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36253. *
  36254. * @param name The material name
  36255. * @param scene The scene the material will be use in.
  36256. */
  36257. function PBRSpecularGlossinessMaterial(name, scene) {
  36258. var _this = _super.call(this, name, scene) || this;
  36259. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36260. return _this;
  36261. }
  36262. /**
  36263. * Return the currrent class name of the material.
  36264. */
  36265. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36266. return "PBRSpecularGlossinessMaterial";
  36267. };
  36268. /**
  36269. * Serialize the material to a parsable JSON object.
  36270. */
  36271. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36272. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36273. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36274. return serializationObject;
  36275. };
  36276. /**
  36277. * Parses a JSON object correponding to the serialize function.
  36278. */
  36279. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36280. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36281. };
  36282. return PBRSpecularGlossinessMaterial;
  36283. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36284. __decorate([
  36285. BABYLON.serializeAsColor3(),
  36286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36287. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36288. __decorate([
  36289. BABYLON.serializeAsTexture(),
  36290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36291. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36292. __decorate([
  36293. BABYLON.serializeAsColor3(),
  36294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36295. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36296. __decorate([
  36297. BABYLON.serialize(),
  36298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36299. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36300. __decorate([
  36301. BABYLON.serializeAsTexture(),
  36302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36303. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36304. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36305. })(BABYLON || (BABYLON = {}));
  36306. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36307. var BABYLON;
  36308. (function (BABYLON) {
  36309. var ShaderMaterial = (function (_super) {
  36310. __extends(ShaderMaterial, _super);
  36311. function ShaderMaterial(name, scene, shaderPath, options) {
  36312. var _this = _super.call(this, name, scene) || this;
  36313. _this._textures = {};
  36314. _this._textureArrays = {};
  36315. _this._floats = {};
  36316. _this._floatsArrays = {};
  36317. _this._colors3 = {};
  36318. _this._colors4 = {};
  36319. _this._vectors2 = {};
  36320. _this._vectors3 = {};
  36321. _this._vectors4 = {};
  36322. _this._matrices = {};
  36323. _this._matrices3x3 = {};
  36324. _this._matrices2x2 = {};
  36325. _this._vectors3Arrays = {};
  36326. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  36327. _this._shaderPath = shaderPath;
  36328. options.needAlphaBlending = options.needAlphaBlending || false;
  36329. options.needAlphaTesting = options.needAlphaTesting || false;
  36330. options.attributes = options.attributes || ["position", "normal", "uv"];
  36331. options.uniforms = options.uniforms || ["worldViewProjection"];
  36332. options.uniformBuffers = options.uniformBuffers || [];
  36333. options.samplers = options.samplers || [];
  36334. options.defines = options.defines || [];
  36335. _this._options = options;
  36336. return _this;
  36337. }
  36338. ShaderMaterial.prototype.getClassName = function () {
  36339. return "ShaderMaterial";
  36340. };
  36341. ShaderMaterial.prototype.needAlphaBlending = function () {
  36342. return this._options.needAlphaBlending;
  36343. };
  36344. ShaderMaterial.prototype.needAlphaTesting = function () {
  36345. return this._options.needAlphaTesting;
  36346. };
  36347. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  36348. if (this._options.uniforms.indexOf(uniformName) === -1) {
  36349. this._options.uniforms.push(uniformName);
  36350. }
  36351. };
  36352. ShaderMaterial.prototype.setTexture = function (name, texture) {
  36353. if (this._options.samplers.indexOf(name) === -1) {
  36354. this._options.samplers.push(name);
  36355. }
  36356. this._textures[name] = texture;
  36357. return this;
  36358. };
  36359. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  36360. if (this._options.samplers.indexOf(name) === -1) {
  36361. this._options.samplers.push(name);
  36362. }
  36363. this._checkUniform(name);
  36364. this._textureArrays[name] = textures;
  36365. return this;
  36366. };
  36367. ShaderMaterial.prototype.setFloat = function (name, value) {
  36368. this._checkUniform(name);
  36369. this._floats[name] = value;
  36370. return this;
  36371. };
  36372. ShaderMaterial.prototype.setFloats = function (name, value) {
  36373. this._checkUniform(name);
  36374. this._floatsArrays[name] = value;
  36375. return this;
  36376. };
  36377. ShaderMaterial.prototype.setColor3 = function (name, value) {
  36378. this._checkUniform(name);
  36379. this._colors3[name] = value;
  36380. return this;
  36381. };
  36382. ShaderMaterial.prototype.setColor4 = function (name, value) {
  36383. this._checkUniform(name);
  36384. this._colors4[name] = value;
  36385. return this;
  36386. };
  36387. ShaderMaterial.prototype.setVector2 = function (name, value) {
  36388. this._checkUniform(name);
  36389. this._vectors2[name] = value;
  36390. return this;
  36391. };
  36392. ShaderMaterial.prototype.setVector3 = function (name, value) {
  36393. this._checkUniform(name);
  36394. this._vectors3[name] = value;
  36395. return this;
  36396. };
  36397. ShaderMaterial.prototype.setVector4 = function (name, value) {
  36398. this._checkUniform(name);
  36399. this._vectors4[name] = value;
  36400. return this;
  36401. };
  36402. ShaderMaterial.prototype.setMatrix = function (name, value) {
  36403. this._checkUniform(name);
  36404. this._matrices[name] = value;
  36405. return this;
  36406. };
  36407. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  36408. this._checkUniform(name);
  36409. this._matrices3x3[name] = value;
  36410. return this;
  36411. };
  36412. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  36413. this._checkUniform(name);
  36414. this._matrices2x2[name] = value;
  36415. return this;
  36416. };
  36417. ShaderMaterial.prototype.setArray3 = function (name, value) {
  36418. this._checkUniform(name);
  36419. this._vectors3Arrays[name] = value;
  36420. return this;
  36421. };
  36422. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  36423. if (!mesh) {
  36424. return true;
  36425. }
  36426. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  36427. return false;
  36428. }
  36429. return false;
  36430. };
  36431. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  36432. var scene = this.getScene();
  36433. var engine = scene.getEngine();
  36434. if (!this.checkReadyOnEveryCall) {
  36435. if (this._renderId === scene.getRenderId()) {
  36436. if (this._checkCache(scene, mesh, useInstances)) {
  36437. return true;
  36438. }
  36439. }
  36440. }
  36441. // Instances
  36442. var defines = [];
  36443. var attribs = [];
  36444. var fallbacks = new BABYLON.EffectFallbacks();
  36445. if (useInstances) {
  36446. defines.push("#define INSTANCES");
  36447. }
  36448. for (var index = 0; index < this._options.defines.length; index++) {
  36449. defines.push(this._options.defines[index]);
  36450. }
  36451. for (var index = 0; index < this._options.attributes.length; index++) {
  36452. attribs.push(this._options.attributes[index]);
  36453. }
  36454. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36455. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36456. defines.push("#define VERTEXCOLOR");
  36457. }
  36458. // Bones
  36459. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  36460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36462. if (mesh.numBoneInfluencers > 4) {
  36463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36465. }
  36466. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36467. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36468. fallbacks.addCPUSkinningFallback(0, mesh);
  36469. }
  36470. else {
  36471. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36472. }
  36473. // Textures
  36474. for (var name in this._textures) {
  36475. if (!this._textures[name].isReady()) {
  36476. return false;
  36477. }
  36478. }
  36479. // Alpha test
  36480. if (engine.getAlphaTesting()) {
  36481. defines.push("#define ALPHATEST");
  36482. }
  36483. var previousEffect = this._effect;
  36484. var join = defines.join("\n");
  36485. this._effect = engine.createEffect(this._shaderPath, {
  36486. attributes: attribs,
  36487. uniformsNames: this._options.uniforms,
  36488. uniformBuffersNames: this._options.uniformBuffers,
  36489. samplers: this._options.samplers,
  36490. defines: join,
  36491. fallbacks: fallbacks,
  36492. onCompiled: this.onCompiled,
  36493. onError: this.onError
  36494. }, engine);
  36495. if (!this._effect.isReady()) {
  36496. return false;
  36497. }
  36498. if (previousEffect !== this._effect) {
  36499. scene.resetCachedMaterial();
  36500. }
  36501. this._renderId = scene.getRenderId();
  36502. return true;
  36503. };
  36504. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36505. var scene = this.getScene();
  36506. if (this._options.uniforms.indexOf("world") !== -1) {
  36507. this._effect.setMatrix("world", world);
  36508. }
  36509. if (this._options.uniforms.indexOf("worldView") !== -1) {
  36510. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  36511. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  36512. }
  36513. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  36514. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  36515. }
  36516. };
  36517. ShaderMaterial.prototype.bind = function (world, mesh) {
  36518. // Std values
  36519. this.bindOnlyWorldMatrix(world);
  36520. if (this.getScene().getCachedMaterial() !== this) {
  36521. if (this._options.uniforms.indexOf("view") !== -1) {
  36522. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  36523. }
  36524. if (this._options.uniforms.indexOf("projection") !== -1) {
  36525. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  36526. }
  36527. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  36528. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36529. }
  36530. // Bones
  36531. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  36532. var name;
  36533. // Texture
  36534. for (name in this._textures) {
  36535. this._effect.setTexture(name, this._textures[name]);
  36536. }
  36537. // Texture arrays
  36538. for (name in this._textureArrays) {
  36539. this._effect.setTextureArray(name, this._textureArrays[name]);
  36540. }
  36541. // Float
  36542. for (name in this._floats) {
  36543. this._effect.setFloat(name, this._floats[name]);
  36544. }
  36545. // Float s
  36546. for (name in this._floatsArrays) {
  36547. this._effect.setArray(name, this._floatsArrays[name]);
  36548. }
  36549. // Color3
  36550. for (name in this._colors3) {
  36551. this._effect.setColor3(name, this._colors3[name]);
  36552. }
  36553. // Color4
  36554. for (name in this._colors4) {
  36555. var color = this._colors4[name];
  36556. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  36557. }
  36558. // Vector2
  36559. for (name in this._vectors2) {
  36560. this._effect.setVector2(name, this._vectors2[name]);
  36561. }
  36562. // Vector3
  36563. for (name in this._vectors3) {
  36564. this._effect.setVector3(name, this._vectors3[name]);
  36565. }
  36566. // Vector4
  36567. for (name in this._vectors4) {
  36568. this._effect.setVector4(name, this._vectors4[name]);
  36569. }
  36570. // Matrix
  36571. for (name in this._matrices) {
  36572. this._effect.setMatrix(name, this._matrices[name]);
  36573. }
  36574. // Matrix 3x3
  36575. for (name in this._matrices3x3) {
  36576. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  36577. }
  36578. // Matrix 2x2
  36579. for (name in this._matrices2x2) {
  36580. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  36581. }
  36582. // Vector3Array
  36583. for (name in this._vectors3Arrays) {
  36584. this._effect.setArray3(name, this._vectors3Arrays[name]);
  36585. }
  36586. }
  36587. this._afterBind(mesh);
  36588. };
  36589. ShaderMaterial.prototype.clone = function (name) {
  36590. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  36591. return newShaderMaterial;
  36592. };
  36593. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36594. if (forceDisposeTextures) {
  36595. var name;
  36596. for (name in this._textures) {
  36597. this._textures[name].dispose();
  36598. }
  36599. for (name in this._textureArrays) {
  36600. var array = this._textureArrays[name];
  36601. for (var index = 0; index < array.length; index++) {
  36602. array[index].dispose();
  36603. }
  36604. }
  36605. }
  36606. this._textures = {};
  36607. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36608. };
  36609. ShaderMaterial.prototype.serialize = function () {
  36610. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36611. serializationObject.customType = "BABYLON.ShaderMaterial";
  36612. serializationObject.options = this._options;
  36613. serializationObject.shaderPath = this._shaderPath;
  36614. var name;
  36615. // Texture
  36616. serializationObject.textures = {};
  36617. for (name in this._textures) {
  36618. serializationObject.textures[name] = this._textures[name].serialize();
  36619. }
  36620. // Texture arrays
  36621. serializationObject.textureArrays = {};
  36622. for (name in this._textureArrays) {
  36623. serializationObject.textureArrays[name] = [];
  36624. var array = this._textureArrays[name];
  36625. for (var index = 0; index < array.length; index++) {
  36626. serializationObject.textureArrays[name].push(array[index].serialize());
  36627. }
  36628. }
  36629. // Float
  36630. serializationObject.floats = {};
  36631. for (name in this._floats) {
  36632. serializationObject.floats[name] = this._floats[name];
  36633. }
  36634. // Float s
  36635. serializationObject.floatArrays = {};
  36636. for (name in this._floatsArrays) {
  36637. serializationObject.floatArrays[name] = this._floatsArrays[name];
  36638. }
  36639. // Color3
  36640. serializationObject.colors3 = {};
  36641. for (name in this._colors3) {
  36642. serializationObject.colors3[name] = this._colors3[name].asArray();
  36643. }
  36644. // Color4
  36645. serializationObject.colors4 = {};
  36646. for (name in this._colors4) {
  36647. serializationObject.colors4[name] = this._colors4[name].asArray();
  36648. }
  36649. // Vector2
  36650. serializationObject.vectors2 = {};
  36651. for (name in this._vectors2) {
  36652. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  36653. }
  36654. // Vector3
  36655. serializationObject.vectors3 = {};
  36656. for (name in this._vectors3) {
  36657. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  36658. }
  36659. // Vector4
  36660. serializationObject.vectors4 = {};
  36661. for (name in this._vectors4) {
  36662. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  36663. }
  36664. // Matrix
  36665. serializationObject.matrices = {};
  36666. for (name in this._matrices) {
  36667. serializationObject.matrices[name] = this._matrices[name].asArray();
  36668. }
  36669. // Matrix 3x3
  36670. serializationObject.matrices3x3 = {};
  36671. for (name in this._matrices3x3) {
  36672. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  36673. }
  36674. // Matrix 2x2
  36675. serializationObject.matrices2x2 = {};
  36676. for (name in this._matrices2x2) {
  36677. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  36678. }
  36679. // Vector3Array
  36680. serializationObject.vectors3Arrays = {};
  36681. for (name in this._vectors3Arrays) {
  36682. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  36683. }
  36684. return serializationObject;
  36685. };
  36686. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  36687. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  36688. var name;
  36689. // Texture
  36690. for (name in source.textures) {
  36691. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  36692. }
  36693. // Texture arrays
  36694. for (name in source.textureArrays) {
  36695. var array = source.textureArrays[name];
  36696. var textureArray = new Array();
  36697. for (var index = 0; index < array.length; index++) {
  36698. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  36699. }
  36700. material.setTextureArray(name, textureArray);
  36701. }
  36702. // Float
  36703. for (name in source.floats) {
  36704. material.setFloat(name, source.floats[name]);
  36705. }
  36706. // Float s
  36707. for (name in source.floatsArrays) {
  36708. material.setFloats(name, source.floatsArrays[name]);
  36709. }
  36710. // Color3
  36711. for (name in source.colors3) {
  36712. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  36713. }
  36714. // Color4
  36715. for (name in source.colors4) {
  36716. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  36717. }
  36718. // Vector2
  36719. for (name in source.vectors2) {
  36720. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  36721. }
  36722. // Vector3
  36723. for (name in source.vectors3) {
  36724. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  36725. }
  36726. // Vector4
  36727. for (name in source.vectors4) {
  36728. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  36729. }
  36730. // Matrix
  36731. for (name in source.matrices) {
  36732. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  36733. }
  36734. // Matrix 3x3
  36735. for (name in source.matrices3x3) {
  36736. material.setMatrix3x3(name, source.matrices3x3[name]);
  36737. }
  36738. // Matrix 2x2
  36739. for (name in source.matrices2x2) {
  36740. material.setMatrix2x2(name, source.matrices2x2[name]);
  36741. }
  36742. // Vector3Array
  36743. for (name in source.vectors3Arrays) {
  36744. material.setArray3(name, source.vectors3Arrays[name]);
  36745. }
  36746. return material;
  36747. };
  36748. return ShaderMaterial;
  36749. }(BABYLON.Material));
  36750. BABYLON.ShaderMaterial = ShaderMaterial;
  36751. })(BABYLON || (BABYLON = {}));
  36752. //# sourceMappingURL=babylon.shaderMaterial.js.map
  36753. var BABYLON;
  36754. (function (BABYLON) {
  36755. var MeshBuilder = (function () {
  36756. function MeshBuilder() {
  36757. }
  36758. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  36759. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  36760. return BABYLON.Mesh.DOUBLESIDE;
  36761. }
  36762. if (orientation === undefined || orientation === null) {
  36763. return BABYLON.Mesh.FRONTSIDE;
  36764. }
  36765. return orientation;
  36766. };
  36767. /**
  36768. * Creates a box mesh.
  36769. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  36770. * The parameter `size` sets the size (float) of each box side (default 1).
  36771. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  36772. * 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).
  36773. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  36774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36775. * 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).
  36776. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36778. */
  36779. MeshBuilder.CreateBox = function (name, options, scene) {
  36780. var box = new BABYLON.Mesh(name, scene);
  36781. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36782. box.sideOrientation = options.sideOrientation;
  36783. var vertexData = BABYLON.VertexData.CreateBox(options);
  36784. vertexData.applyToMesh(box, options.updatable);
  36785. return box;
  36786. };
  36787. /**
  36788. * Creates a sphere mesh.
  36789. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  36790. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  36791. * 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`).
  36792. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  36793. * 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
  36794. * 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).
  36795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36796. * 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).
  36797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36799. */
  36800. MeshBuilder.CreateSphere = function (name, options, scene) {
  36801. var sphere = new BABYLON.Mesh(name, scene);
  36802. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36803. sphere.sideOrientation = options.sideOrientation;
  36804. var vertexData = BABYLON.VertexData.CreateSphere(options);
  36805. vertexData.applyToMesh(sphere, options.updatable);
  36806. return sphere;
  36807. };
  36808. /**
  36809. * Creates a plane polygonal mesh. By default, this is a disc.
  36810. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  36811. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  36812. * 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.
  36813. * 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
  36814. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36815. * 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).
  36816. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36817. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36818. */
  36819. MeshBuilder.CreateDisc = function (name, options, scene) {
  36820. var disc = new BABYLON.Mesh(name, scene);
  36821. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36822. disc.sideOrientation = options.sideOrientation;
  36823. var vertexData = BABYLON.VertexData.CreateDisc(options);
  36824. vertexData.applyToMesh(disc, options.updatable);
  36825. return disc;
  36826. };
  36827. /**
  36828. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  36829. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  36830. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  36831. * 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`).
  36832. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  36833. * 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.
  36834. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36835. * 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).
  36836. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36838. */
  36839. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  36840. var sphere = new BABYLON.Mesh(name, scene);
  36841. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36842. sphere.sideOrientation = options.sideOrientation;
  36843. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  36844. vertexData.applyToMesh(sphere, options.updatable);
  36845. return sphere;
  36846. };
  36847. ;
  36848. /**
  36849. * Creates a ribbon mesh.
  36850. * 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.
  36851. *
  36852. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  36853. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  36854. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  36855. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  36856. * 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.
  36857. * 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.
  36858. * 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
  36859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36860. * 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).
  36861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36862. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  36863. * 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.
  36864. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  36865. * 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
  36866. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  36867. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  36868. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36869. */
  36870. MeshBuilder.CreateRibbon = function (name, options, scene) {
  36871. var pathArray = options.pathArray;
  36872. var closeArray = options.closeArray;
  36873. var closePath = options.closePath;
  36874. var offset = options.offset;
  36875. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36876. var instance = options.instance;
  36877. var updatable = options.updatable;
  36878. if (instance) {
  36879. // positionFunction : ribbon case
  36880. // only pathArray and sideOrientation parameters are taken into account for positions update
  36881. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  36882. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  36883. var positionFunction = function (positions) {
  36884. var minlg = pathArray[0].length;
  36885. var i = 0;
  36886. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  36887. for (var si = 1; si <= ns; si++) {
  36888. for (var p = 0; p < pathArray.length; p++) {
  36889. var path = pathArray[p];
  36890. var l = path.length;
  36891. minlg = (minlg < l) ? minlg : l;
  36892. var j = 0;
  36893. while (j < minlg) {
  36894. positions[i] = path[j].x;
  36895. positions[i + 1] = path[j].y;
  36896. positions[i + 2] = path[j].z;
  36897. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  36898. BABYLON.Tmp.Vector3[0].x = path[j].x;
  36899. }
  36900. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  36901. BABYLON.Tmp.Vector3[1].x = path[j].x;
  36902. }
  36903. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  36904. BABYLON.Tmp.Vector3[0].y = path[j].y;
  36905. }
  36906. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  36907. BABYLON.Tmp.Vector3[1].y = path[j].y;
  36908. }
  36909. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  36910. BABYLON.Tmp.Vector3[0].z = path[j].z;
  36911. }
  36912. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  36913. BABYLON.Tmp.Vector3[1].z = path[j].z;
  36914. }
  36915. j++;
  36916. i += 3;
  36917. }
  36918. if (instance._closePath) {
  36919. positions[i] = path[0].x;
  36920. positions[i + 1] = path[0].y;
  36921. positions[i + 2] = path[0].z;
  36922. i += 3;
  36923. }
  36924. }
  36925. }
  36926. };
  36927. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36928. positionFunction(positions);
  36929. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  36930. instance._boundingInfo.update(instance._worldMatrix);
  36931. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  36932. if (options.colors) {
  36933. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36934. for (var c = 0; c < options.colors.length; c++) {
  36935. colors[c * 4] = options.colors[c].r;
  36936. colors[c * 4 + 1] = options.colors[c].g;
  36937. colors[c * 4 + 2] = options.colors[c].b;
  36938. colors[c * 4 + 3] = options.colors[c].a;
  36939. }
  36940. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  36941. }
  36942. if (options.uvs) {
  36943. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36944. for (var i = 0; i < options.uvs.length; i++) {
  36945. uvs[i * 2] = options.uvs[i].x;
  36946. uvs[i * 2 + 1] = options.uvs[i].y;
  36947. }
  36948. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  36949. }
  36950. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  36951. var indices = instance.getIndices();
  36952. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36953. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  36954. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  36955. if (instance._closePath) {
  36956. var indexFirst = 0;
  36957. var indexLast = 0;
  36958. for (var p = 0; p < pathArray.length; p++) {
  36959. indexFirst = instance._idx[p] * 3;
  36960. if (p + 1 < pathArray.length) {
  36961. indexLast = (instance._idx[p + 1] - 1) * 3;
  36962. }
  36963. else {
  36964. indexLast = normals.length - 3;
  36965. }
  36966. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36967. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36968. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36969. normals[indexLast] = normals[indexFirst];
  36970. normals[indexLast + 1] = normals[indexFirst + 1];
  36971. normals[indexLast + 2] = normals[indexFirst + 2];
  36972. }
  36973. }
  36974. if (!(instance.areNormalsFrozen)) {
  36975. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  36976. }
  36977. }
  36978. return instance;
  36979. }
  36980. else {
  36981. var ribbon = new BABYLON.Mesh(name, scene);
  36982. ribbon.sideOrientation = sideOrientation;
  36983. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  36984. if (closePath) {
  36985. ribbon._idx = vertexData._idx;
  36986. }
  36987. ribbon._closePath = closePath;
  36988. ribbon._closeArray = closeArray;
  36989. vertexData.applyToMesh(ribbon, updatable);
  36990. return ribbon;
  36991. }
  36992. };
  36993. /**
  36994. * Creates a cylinder or a cone mesh.
  36995. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  36996. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  36997. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  36998. * 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.
  36999. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37000. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37001. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37002. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37003. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37004. * 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).
  37005. * 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
  37006. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37007. * 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
  37008. * 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.
  37009. * If `enclose` is false, a ring surface is one element.
  37010. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37011. * 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
  37012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37013. * 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).
  37014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37016. */
  37017. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37018. var cylinder = new BABYLON.Mesh(name, scene);
  37019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37020. cylinder.sideOrientation = options.sideOrientation;
  37021. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37022. vertexData.applyToMesh(cylinder, options.updatable);
  37023. return cylinder;
  37024. };
  37025. /**
  37026. * Creates a torus mesh.
  37027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37028. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37029. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37030. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37032. * 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).
  37033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37035. */
  37036. MeshBuilder.CreateTorus = function (name, options, scene) {
  37037. var torus = new BABYLON.Mesh(name, scene);
  37038. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37039. torus.sideOrientation = options.sideOrientation;
  37040. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37041. vertexData.applyToMesh(torus, options.updatable);
  37042. return torus;
  37043. };
  37044. /**
  37045. * Creates a torus knot mesh.
  37046. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37047. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37048. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37049. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37050. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37052. * 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).
  37053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37055. */
  37056. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  37057. var torusKnot = new BABYLON.Mesh(name, scene);
  37058. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37059. torusKnot.sideOrientation = options.sideOrientation;
  37060. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  37061. vertexData.applyToMesh(torusKnot, options.updatable);
  37062. return torusKnot;
  37063. };
  37064. /**
  37065. * Creates a line system mesh.
  37066. * A line system is a pool of many lines gathered in a single mesh.
  37067. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  37068. * 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.
  37069. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  37070. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  37071. * 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
  37072. * 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
  37073. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  37074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37075. */
  37076. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  37077. var instance = options.instance;
  37078. var lines = options.lines;
  37079. if (instance) {
  37080. var positionFunction = function (positions) {
  37081. var i = 0;
  37082. for (var l = 0; l < lines.length; l++) {
  37083. var points = lines[l];
  37084. for (var p = 0; p < points.length; p++) {
  37085. positions[i] = points[p].x;
  37086. positions[i + 1] = points[p].y;
  37087. positions[i + 2] = points[p].z;
  37088. i += 3;
  37089. }
  37090. }
  37091. };
  37092. instance.updateMeshPositions(positionFunction, false);
  37093. return instance;
  37094. }
  37095. // line system creation
  37096. var lineSystem = new BABYLON.LinesMesh(name, scene);
  37097. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  37098. vertexData.applyToMesh(lineSystem, options.updatable);
  37099. return lineSystem;
  37100. };
  37101. /**
  37102. * Creates a line mesh.
  37103. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  37104. * 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.
  37105. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37106. * The parameter `points` is an array successive Vector3.
  37107. * 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
  37108. * When updating an instance, remember that only point positions can change, not the number of points.
  37109. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37110. */
  37111. MeshBuilder.CreateLines = function (name, options, scene) {
  37112. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  37113. return lines;
  37114. };
  37115. /**
  37116. * Creates a dashed line mesh.
  37117. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  37118. * 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.
  37119. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37120. * The parameter `points` is an array successive Vector3.
  37121. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  37122. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  37123. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  37124. * 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
  37125. * When updating an instance, remember that only point positions can change, not the number of points.
  37126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37127. */
  37128. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  37129. var points = options.points;
  37130. var instance = options.instance;
  37131. var gapSize = options.gapSize;
  37132. var dashNb = options.dashNb;
  37133. var dashSize = options.dashSize;
  37134. if (instance) {
  37135. var positionFunction = function (positions) {
  37136. var curvect = BABYLON.Vector3.Zero();
  37137. var nbSeg = positions.length / 6;
  37138. var lg = 0;
  37139. var nb = 0;
  37140. var shft = 0;
  37141. var dashshft = 0;
  37142. var curshft = 0;
  37143. var p = 0;
  37144. var i = 0;
  37145. var j = 0;
  37146. for (i = 0; i < points.length - 1; i++) {
  37147. points[i + 1].subtractToRef(points[i], curvect);
  37148. lg += curvect.length();
  37149. }
  37150. shft = lg / nbSeg;
  37151. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  37152. for (i = 0; i < points.length - 1; i++) {
  37153. points[i + 1].subtractToRef(points[i], curvect);
  37154. nb = Math.floor(curvect.length() / shft);
  37155. curvect.normalize();
  37156. j = 0;
  37157. while (j < nb && p < positions.length) {
  37158. curshft = shft * j;
  37159. positions[p] = points[i].x + curshft * curvect.x;
  37160. positions[p + 1] = points[i].y + curshft * curvect.y;
  37161. positions[p + 2] = points[i].z + curshft * curvect.z;
  37162. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  37163. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  37164. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  37165. p += 6;
  37166. j++;
  37167. }
  37168. }
  37169. while (p < positions.length) {
  37170. positions[p] = points[i].x;
  37171. positions[p + 1] = points[i].y;
  37172. positions[p + 2] = points[i].z;
  37173. p += 3;
  37174. }
  37175. };
  37176. instance.updateMeshPositions(positionFunction, false);
  37177. return instance;
  37178. }
  37179. // dashed lines creation
  37180. var dashedLines = new BABYLON.LinesMesh(name, scene);
  37181. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  37182. vertexData.applyToMesh(dashedLines, options.updatable);
  37183. dashedLines.dashSize = dashSize;
  37184. dashedLines.gapSize = gapSize;
  37185. return dashedLines;
  37186. };
  37187. /**
  37188. * Creates an extruded shape mesh.
  37189. * 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.
  37190. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  37191. *
  37192. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37193. * 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
  37194. * extruded along the Z axis.
  37195. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37196. * 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.
  37197. * The parameter `scale` (float, default 1) is the value to scale the shape.
  37198. * 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
  37199. * 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
  37200. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37202. * 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).
  37203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37204. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37206. */
  37207. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  37208. var path = options.path;
  37209. var shape = options.shape;
  37210. var scale = options.scale || 1;
  37211. var rotation = options.rotation || 0;
  37212. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37213. var updatable = options.updatable;
  37214. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37215. var instance = options.instance;
  37216. var invertUV = options.invertUV || false;
  37217. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37218. };
  37219. /**
  37220. * Creates an custom extruded shape mesh.
  37221. * 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.
  37222. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  37223. *
  37224. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37225. * 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
  37226. * extruded along the Z axis.
  37227. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37228. * 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
  37229. * and the distance of this point from the begining of the path :
  37230. * ```javascript
  37231. * var rotationFunction = function(i, distance) {
  37232. * // do things
  37233. * return rotationValue; }
  37234. * ```
  37235. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  37236. * 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
  37237. * and the distance of this point from the begining of the path :
  37238. * ```javascript
  37239. * var scaleFunction = function(i, distance) {
  37240. * // do things
  37241. * return scaleValue;}
  37242. * ```
  37243. * It must returns a float value that will be the scale value applied to the shape on each path point.
  37244. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  37245. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  37246. * 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
  37247. * 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
  37248. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37250. * 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).
  37251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37252. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37254. */
  37255. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  37256. var path = options.path;
  37257. var shape = options.shape;
  37258. var scaleFunction = options.scaleFunction || (function () { return 1; });
  37259. var rotationFunction = options.rotationFunction || (function () { return 0; });
  37260. var ribbonCloseArray = options.ribbonCloseArray || false;
  37261. var ribbonClosePath = options.ribbonClosePath || false;
  37262. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37263. var updatable = options.updatable;
  37264. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37265. var instance = options.instance;
  37266. var invertUV = options.invertUV || false;
  37267. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37268. };
  37269. /**
  37270. * Creates lathe mesh.
  37271. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  37272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  37273. *
  37274. * 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
  37275. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  37276. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  37277. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  37278. * 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.
  37279. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  37280. * 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
  37281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37282. * 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).
  37283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37284. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37286. */
  37287. MeshBuilder.CreateLathe = function (name, options, scene) {
  37288. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  37289. var closed = (options.closed === undefined) ? true : options.closed;
  37290. var shape = options.shape;
  37291. var radius = options.radius || 1;
  37292. var tessellation = options.tessellation || 64;
  37293. var updatable = options.updatable;
  37294. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37295. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37296. var pi2 = Math.PI * 2;
  37297. var paths = new Array();
  37298. var invertUV = options.invertUV || false;
  37299. var i = 0;
  37300. var p = 0;
  37301. var step = pi2 / tessellation * arc;
  37302. var rotated;
  37303. var path = new Array();
  37304. ;
  37305. for (i = 0; i <= tessellation; i++) {
  37306. var path = [];
  37307. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  37308. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  37309. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  37310. }
  37311. for (p = 0; p < shape.length; p++) {
  37312. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  37313. path.push(rotated);
  37314. }
  37315. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  37316. 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));
  37317. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  37318. }
  37319. paths.push(path);
  37320. }
  37321. // lathe ribbon
  37322. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37323. return lathe;
  37324. };
  37325. /**
  37326. * Creates a plane mesh.
  37327. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37328. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  37329. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  37330. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  37331. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37332. * 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).
  37333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37335. */
  37336. MeshBuilder.CreatePlane = function (name, options, scene) {
  37337. var plane = new BABYLON.Mesh(name, scene);
  37338. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37339. plane.sideOrientation = options.sideOrientation;
  37340. var vertexData = BABYLON.VertexData.CreatePlane(options);
  37341. vertexData.applyToMesh(plane, options.updatable);
  37342. if (options.sourcePlane) {
  37343. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  37344. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  37345. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  37346. plane.rotate(vectorProduct, product);
  37347. }
  37348. return plane;
  37349. };
  37350. /**
  37351. * Creates a ground mesh.
  37352. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37353. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  37354. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  37355. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37356. */
  37357. MeshBuilder.CreateGround = function (name, options, scene) {
  37358. var ground = new BABYLON.GroundMesh(name, scene);
  37359. ground._setReady(false);
  37360. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37361. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37362. ground._width = options.width || 1;
  37363. ground._height = options.height || 1;
  37364. ground._maxX = ground._width / 2;
  37365. ground._maxZ = ground._height / 2;
  37366. ground._minX = -ground._maxX;
  37367. ground._minZ = -ground._maxZ;
  37368. var vertexData = BABYLON.VertexData.CreateGround(options);
  37369. vertexData.applyToMesh(ground, options.updatable);
  37370. ground._setReady(true);
  37371. return ground;
  37372. };
  37373. /**
  37374. * Creates a tiled ground mesh.
  37375. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  37376. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  37377. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  37378. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  37379. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  37380. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  37381. * numbers of subdivisions on the ground width and height of each tile.
  37382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37383. */
  37384. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  37385. var tiledGround = new BABYLON.Mesh(name, scene);
  37386. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  37387. vertexData.applyToMesh(tiledGround, options.updatable);
  37388. return tiledGround;
  37389. };
  37390. /**
  37391. * Creates a ground mesh from a height map.
  37392. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  37393. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  37394. * The parameter `url` sets the URL of the height map image resource.
  37395. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  37396. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  37397. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  37398. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  37399. * 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.
  37400. * 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).
  37401. * This function is passed the newly built mesh :
  37402. * ```javascript
  37403. * function(mesh) { // do things
  37404. * return; }
  37405. * ```
  37406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37407. */
  37408. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  37409. var width = options.width || 10.0;
  37410. var height = options.height || 10.0;
  37411. var subdivisions = options.subdivisions || 1 | 0;
  37412. var minHeight = options.minHeight || 0.0;
  37413. var maxHeight = options.maxHeight || 10.0;
  37414. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37415. var updatable = options.updatable;
  37416. var onReady = options.onReady;
  37417. var ground = new BABYLON.GroundMesh(name, scene);
  37418. ground._subdivisionsX = subdivisions;
  37419. ground._subdivisionsY = subdivisions;
  37420. ground._width = width;
  37421. ground._height = height;
  37422. ground._maxX = ground._width / 2.0;
  37423. ground._maxZ = ground._height / 2.0;
  37424. ground._minX = -ground._maxX;
  37425. ground._minZ = -ground._maxZ;
  37426. ground._setReady(false);
  37427. var onload = function (img) {
  37428. // Getting height map data
  37429. var canvas = document.createElement("canvas");
  37430. var context = canvas.getContext("2d");
  37431. var bufferWidth = img.width;
  37432. var bufferHeight = img.height;
  37433. canvas.width = bufferWidth;
  37434. canvas.height = bufferHeight;
  37435. context.drawImage(img, 0, 0);
  37436. // Create VertexData from map data
  37437. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  37438. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  37439. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  37440. width: width, height: height,
  37441. subdivisions: subdivisions,
  37442. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  37443. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  37444. });
  37445. vertexData.applyToMesh(ground, updatable);
  37446. ground._setReady(true);
  37447. //execute ready callback, if set
  37448. if (onReady) {
  37449. onReady(ground);
  37450. }
  37451. };
  37452. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  37453. return ground;
  37454. };
  37455. /**
  37456. * Creates a polygon mesh.
  37457. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  37458. * 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.
  37459. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37461. * 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).
  37462. * Remember you can only change the shape positions, not their number when updating a polygon.
  37463. */
  37464. MeshBuilder.CreatePolygon = function (name, options, scene) {
  37465. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37466. var shape = options.shape;
  37467. var holes = options.holes || [];
  37468. var depth = options.depth || 0;
  37469. var contours = [];
  37470. var hole = [];
  37471. for (var i = 0; i < shape.length; i++) {
  37472. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  37473. }
  37474. var epsilon = 0.00000001;
  37475. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  37476. contours.pop();
  37477. }
  37478. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  37479. for (var hNb = 0; hNb < holes.length; hNb++) {
  37480. hole = [];
  37481. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  37482. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  37483. }
  37484. polygonTriangulation.addHole(hole);
  37485. }
  37486. var polygon = polygonTriangulation.build(options.updatable, depth);
  37487. polygon.sideOrientation = options.sideOrientation;
  37488. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  37489. vertexData.applyToMesh(polygon, options.updatable);
  37490. return polygon;
  37491. };
  37492. ;
  37493. /**
  37494. * Creates an extruded polygon mesh, with depth in the Y direction.
  37495. * 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).
  37496. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37497. */
  37498. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  37499. return MeshBuilder.CreatePolygon(name, options, scene);
  37500. };
  37501. ;
  37502. /**
  37503. * Creates a tube mesh.
  37504. * 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.
  37505. *
  37506. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  37507. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  37508. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  37509. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  37510. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  37511. * 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.
  37512. * It must return a radius value (positive float) :
  37513. * ```javascript
  37514. * var radiusFunction = function(i, distance) {
  37515. * // do things
  37516. * return radius; }
  37517. * ```
  37518. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  37519. * 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
  37520. * 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
  37521. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37522. * 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).
  37523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37524. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37526. */
  37527. MeshBuilder.CreateTube = function (name, options, scene) {
  37528. var path = options.path;
  37529. var radius = options.radius || 1.0;
  37530. var tessellation = options.tessellation || 64 | 0;
  37531. var radiusFunction = options.radiusFunction;
  37532. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37533. var invertUV = options.invertUV || false;
  37534. var updatable = options.updatable;
  37535. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37536. var instance = options.instance;
  37537. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  37538. // tube geometry
  37539. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  37540. var tangents = path3D.getTangents();
  37541. var normals = path3D.getNormals();
  37542. var distances = path3D.getDistances();
  37543. var pi2 = Math.PI * 2;
  37544. var step = pi2 / tessellation * arc;
  37545. var returnRadius = function () { return radius; };
  37546. var radiusFunctionFinal = radiusFunction || returnRadius;
  37547. var circlePath;
  37548. var rad;
  37549. var normal;
  37550. var rotated;
  37551. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37552. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37553. for (var i = 0; i < path.length; i++) {
  37554. rad = radiusFunctionFinal(i, distances[i]); // current radius
  37555. circlePath = Array(); // current circle array
  37556. normal = normals[i]; // current normal
  37557. for (var t = 0; t < tessellation; t++) {
  37558. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  37559. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  37560. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  37561. rotated.scaleInPlace(rad).addInPlace(path[i]);
  37562. circlePath[t] = rotated;
  37563. }
  37564. circlePaths[index] = circlePath;
  37565. index++;
  37566. }
  37567. // cap
  37568. var capPath = function (nbPoints, pathIndex) {
  37569. var pointCap = Array();
  37570. for (var i = 0; i < nbPoints; i++) {
  37571. pointCap.push(path[pathIndex]);
  37572. }
  37573. return pointCap;
  37574. };
  37575. switch (cap) {
  37576. case BABYLON.Mesh.NO_CAP:
  37577. break;
  37578. case BABYLON.Mesh.CAP_START:
  37579. circlePaths[0] = capPath(tessellation, 0);
  37580. circlePaths[1] = circlePaths[2].slice(0);
  37581. break;
  37582. case BABYLON.Mesh.CAP_END:
  37583. circlePaths[index] = circlePaths[index - 1].slice(0);
  37584. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37585. break;
  37586. case BABYLON.Mesh.CAP_ALL:
  37587. circlePaths[0] = capPath(tessellation, 0);
  37588. circlePaths[1] = circlePaths[2].slice(0);
  37589. circlePaths[index] = circlePaths[index - 1].slice(0);
  37590. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37591. break;
  37592. default:
  37593. break;
  37594. }
  37595. return circlePaths;
  37596. };
  37597. var path3D;
  37598. var pathArray;
  37599. if (instance) {
  37600. var arc = options.arc || instance.arc;
  37601. path3D = (instance.path3D).update(path);
  37602. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  37603. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  37604. instance.path3D = path3D;
  37605. instance.pathArray = pathArray;
  37606. instance.arc = arc;
  37607. return instance;
  37608. }
  37609. // tube creation
  37610. path3D = new BABYLON.Path3D(path);
  37611. var newPathArray = new Array();
  37612. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37613. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  37614. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37615. tube.pathArray = pathArray;
  37616. tube.path3D = path3D;
  37617. tube.tessellation = tessellation;
  37618. tube.cap = cap;
  37619. tube.arc = options.arc;
  37620. return tube;
  37621. };
  37622. /**
  37623. * Creates a polyhedron mesh.
  37624. *
  37625. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  37626. * 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
  37627. * to choose the wanted type.
  37628. * The parameter `size` (positive float, default 1) sets the polygon size.
  37629. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  37630. * 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`.
  37631. * 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
  37632. * 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)`).
  37633. * 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
  37634. * 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.
  37635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37636. * 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).
  37637. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37638. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37639. */
  37640. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  37641. var polyhedron = new BABYLON.Mesh(name, scene);
  37642. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37643. polyhedron.sideOrientation = options.sideOrientation;
  37644. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  37645. vertexData.applyToMesh(polyhedron, options.updatable);
  37646. return polyhedron;
  37647. };
  37648. /**
  37649. * Creates a decal mesh.
  37650. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  37651. * 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.
  37652. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  37653. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  37654. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  37655. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  37656. */
  37657. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  37658. var indices = sourceMesh.getIndices();
  37659. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37660. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37661. var position = options.position || BABYLON.Vector3.Zero();
  37662. var normal = options.normal || BABYLON.Vector3.Up();
  37663. var size = options.size || BABYLON.Vector3.One();
  37664. var angle = options.angle || 0;
  37665. // Getting correct rotation
  37666. if (!normal) {
  37667. var target = new BABYLON.Vector3(0, 0, 1);
  37668. var camera = sourceMesh.getScene().activeCamera;
  37669. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  37670. normal = camera.globalPosition.subtract(cameraWorldTarget);
  37671. }
  37672. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  37673. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  37674. var pitch = Math.atan2(normal.y, len);
  37675. // Matrix
  37676. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  37677. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  37678. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  37679. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  37680. var vertexData = new BABYLON.VertexData();
  37681. vertexData.indices = [];
  37682. vertexData.positions = [];
  37683. vertexData.normals = [];
  37684. vertexData.uvs = [];
  37685. var currentVertexDataIndex = 0;
  37686. var extractDecalVector3 = function (indexId) {
  37687. var vertexId = indices[indexId];
  37688. var result = new BABYLON.PositionNormalVertex();
  37689. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  37690. // Send vector to decal local world
  37691. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  37692. // Get normal
  37693. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  37694. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  37695. return result;
  37696. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  37697. var clip = function (vertices, axis) {
  37698. if (vertices.length === 0) {
  37699. return vertices;
  37700. }
  37701. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  37702. var clipVertices = function (v0, v1) {
  37703. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  37704. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  37705. };
  37706. var result = new Array();
  37707. for (var index = 0; index < vertices.length; index += 3) {
  37708. var v1Out;
  37709. var v2Out;
  37710. var v3Out;
  37711. var total = 0;
  37712. var nV1, nV2, nV3, nV4;
  37713. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  37714. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  37715. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  37716. v1Out = d1 > 0;
  37717. v2Out = d2 > 0;
  37718. v3Out = d3 > 0;
  37719. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  37720. switch (total) {
  37721. case 0:
  37722. result.push(vertices[index]);
  37723. result.push(vertices[index + 1]);
  37724. result.push(vertices[index + 2]);
  37725. break;
  37726. case 1:
  37727. if (v1Out) {
  37728. nV1 = vertices[index + 1];
  37729. nV2 = vertices[index + 2];
  37730. nV3 = clipVertices(vertices[index], nV1);
  37731. nV4 = clipVertices(vertices[index], nV2);
  37732. }
  37733. if (v2Out) {
  37734. nV1 = vertices[index];
  37735. nV2 = vertices[index + 2];
  37736. nV3 = clipVertices(vertices[index + 1], nV1);
  37737. nV4 = clipVertices(vertices[index + 1], nV2);
  37738. result.push(nV3);
  37739. result.push(nV2.clone());
  37740. result.push(nV1.clone());
  37741. result.push(nV2.clone());
  37742. result.push(nV3.clone());
  37743. result.push(nV4);
  37744. break;
  37745. }
  37746. if (v3Out) {
  37747. nV1 = vertices[index];
  37748. nV2 = vertices[index + 1];
  37749. nV3 = clipVertices(vertices[index + 2], nV1);
  37750. nV4 = clipVertices(vertices[index + 2], nV2);
  37751. }
  37752. result.push(nV1.clone());
  37753. result.push(nV2.clone());
  37754. result.push(nV3);
  37755. result.push(nV4);
  37756. result.push(nV3.clone());
  37757. result.push(nV2.clone());
  37758. break;
  37759. case 2:
  37760. if (!v1Out) {
  37761. nV1 = vertices[index].clone();
  37762. nV2 = clipVertices(nV1, vertices[index + 1]);
  37763. nV3 = clipVertices(nV1, vertices[index + 2]);
  37764. result.push(nV1);
  37765. result.push(nV2);
  37766. result.push(nV3);
  37767. }
  37768. if (!v2Out) {
  37769. nV1 = vertices[index + 1].clone();
  37770. nV2 = clipVertices(nV1, vertices[index + 2]);
  37771. nV3 = clipVertices(nV1, vertices[index]);
  37772. result.push(nV1);
  37773. result.push(nV2);
  37774. result.push(nV3);
  37775. }
  37776. if (!v3Out) {
  37777. nV1 = vertices[index + 2].clone();
  37778. nV2 = clipVertices(nV1, vertices[index]);
  37779. nV3 = clipVertices(nV1, vertices[index + 1]);
  37780. result.push(nV1);
  37781. result.push(nV2);
  37782. result.push(nV3);
  37783. }
  37784. break;
  37785. case 3:
  37786. break;
  37787. }
  37788. }
  37789. return result;
  37790. };
  37791. for (var index = 0; index < indices.length; index += 3) {
  37792. var faceVertices = new Array();
  37793. faceVertices.push(extractDecalVector3(index));
  37794. faceVertices.push(extractDecalVector3(index + 1));
  37795. faceVertices.push(extractDecalVector3(index + 2));
  37796. // Clip
  37797. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  37798. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  37799. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  37800. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  37801. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  37802. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  37803. if (faceVertices.length === 0) {
  37804. continue;
  37805. }
  37806. // Add UVs and get back to world
  37807. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  37808. var vertex = faceVertices[vIndex];
  37809. //TODO check for Int32Array | Uint32Array | Uint16Array
  37810. vertexData.indices.push(currentVertexDataIndex);
  37811. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  37812. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  37813. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  37814. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  37815. currentVertexDataIndex++;
  37816. }
  37817. }
  37818. // Return mesh
  37819. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  37820. vertexData.applyToMesh(decal);
  37821. decal.position = position.clone();
  37822. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  37823. return decal;
  37824. };
  37825. // Privates
  37826. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  37827. // extrusion geometry
  37828. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  37829. var tangents = path3D.getTangents();
  37830. var normals = path3D.getNormals();
  37831. var binormals = path3D.getBinormals();
  37832. var distances = path3D.getDistances();
  37833. var angle = 0;
  37834. var returnScale = function () { return scale; };
  37835. var returnRotation = function () { return rotation; };
  37836. var rotate = custom ? rotateFunction : returnRotation;
  37837. var scl = custom ? scaleFunction : returnScale;
  37838. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37839. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37840. for (var i = 0; i < curve.length; i++) {
  37841. var shapePath = new Array();
  37842. var angleStep = rotate(i, distances[i]);
  37843. var scaleRatio = scl(i, distances[i]);
  37844. for (var p = 0; p < shape.length; p++) {
  37845. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  37846. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  37847. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  37848. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  37849. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  37850. shapePath[p] = rotated;
  37851. }
  37852. shapePaths[index] = shapePath;
  37853. angle += angleStep;
  37854. index++;
  37855. }
  37856. // cap
  37857. var capPath = function (shapePath) {
  37858. var pointCap = Array();
  37859. var barycenter = BABYLON.Vector3.Zero();
  37860. var i;
  37861. for (i = 0; i < shapePath.length; i++) {
  37862. barycenter.addInPlace(shapePath[i]);
  37863. }
  37864. barycenter.scaleInPlace(1.0 / shapePath.length);
  37865. for (i = 0; i < shapePath.length; i++) {
  37866. pointCap.push(barycenter);
  37867. }
  37868. return pointCap;
  37869. };
  37870. switch (cap) {
  37871. case BABYLON.Mesh.NO_CAP:
  37872. break;
  37873. case BABYLON.Mesh.CAP_START:
  37874. shapePaths[0] = capPath(shapePaths[2]);
  37875. shapePaths[1] = shapePaths[2];
  37876. break;
  37877. case BABYLON.Mesh.CAP_END:
  37878. shapePaths[index] = shapePaths[index - 1];
  37879. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  37880. break;
  37881. case BABYLON.Mesh.CAP_ALL:
  37882. shapePaths[0] = capPath(shapePaths[2]);
  37883. shapePaths[1] = shapePaths[2];
  37884. shapePaths[index] = shapePaths[index - 1];
  37885. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  37886. break;
  37887. default:
  37888. break;
  37889. }
  37890. return shapePaths;
  37891. };
  37892. var path3D;
  37893. var pathArray;
  37894. if (instance) {
  37895. path3D = (instance.path3D).update(curve);
  37896. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  37897. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  37898. return instance;
  37899. }
  37900. // extruded shape creation
  37901. path3D = new BABYLON.Path3D(curve);
  37902. var newShapePaths = new Array();
  37903. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37904. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  37905. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  37906. extrudedGeneric.pathArray = pathArray;
  37907. extrudedGeneric.path3D = path3D;
  37908. extrudedGeneric.cap = cap;
  37909. return extrudedGeneric;
  37910. };
  37911. return MeshBuilder;
  37912. }());
  37913. BABYLON.MeshBuilder = MeshBuilder;
  37914. })(BABYLON || (BABYLON = {}));
  37915. //# sourceMappingURL=babylon.meshBuilder.js.map
  37916. var BABYLON;
  37917. (function (BABYLON) {
  37918. var Layer = (function () {
  37919. function Layer(name, imgUrl, scene, isBackground, color) {
  37920. this.name = name;
  37921. this.scale = new BABYLON.Vector2(1, 1);
  37922. this.offset = new BABYLON.Vector2(0, 0);
  37923. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  37924. this.layerMask = 0x0FFFFFFF;
  37925. this._vertexBuffers = {};
  37926. // Events
  37927. /**
  37928. * An event triggered when the layer is disposed.
  37929. * @type {BABYLON.Observable}
  37930. */
  37931. this.onDisposeObservable = new BABYLON.Observable();
  37932. /**
  37933. * An event triggered before rendering the scene
  37934. * @type {BABYLON.Observable}
  37935. */
  37936. this.onBeforeRenderObservable = new BABYLON.Observable();
  37937. /**
  37938. * An event triggered after rendering the scene
  37939. * @type {BABYLON.Observable}
  37940. */
  37941. this.onAfterRenderObservable = new BABYLON.Observable();
  37942. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  37943. this.isBackground = isBackground === undefined ? true : isBackground;
  37944. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  37945. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37946. this._scene.layers.push(this);
  37947. var engine = this._scene.getEngine();
  37948. // VBO
  37949. var vertices = [];
  37950. vertices.push(1, 1);
  37951. vertices.push(-1, 1);
  37952. vertices.push(-1, -1);
  37953. vertices.push(1, -1);
  37954. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37955. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  37956. // Indices
  37957. var indices = [];
  37958. indices.push(0);
  37959. indices.push(1);
  37960. indices.push(2);
  37961. indices.push(0);
  37962. indices.push(2);
  37963. indices.push(3);
  37964. this._indexBuffer = engine.createIndexBuffer(indices);
  37965. // Effects
  37966. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  37967. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  37968. }
  37969. Object.defineProperty(Layer.prototype, "onDispose", {
  37970. set: function (callback) {
  37971. if (this._onDisposeObserver) {
  37972. this.onDisposeObservable.remove(this._onDisposeObserver);
  37973. }
  37974. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37975. },
  37976. enumerable: true,
  37977. configurable: true
  37978. });
  37979. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  37980. set: function (callback) {
  37981. if (this._onBeforeRenderObserver) {
  37982. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  37983. }
  37984. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  37985. },
  37986. enumerable: true,
  37987. configurable: true
  37988. });
  37989. Object.defineProperty(Layer.prototype, "onAfterRender", {
  37990. set: function (callback) {
  37991. if (this._onAfterRenderObserver) {
  37992. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  37993. }
  37994. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  37995. },
  37996. enumerable: true,
  37997. configurable: true
  37998. });
  37999. Layer.prototype.render = function () {
  38000. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  38001. // Check
  38002. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  38003. return;
  38004. var engine = this._scene.getEngine();
  38005. this.onBeforeRenderObservable.notifyObservers(this);
  38006. // Render
  38007. engine.enableEffect(currentEffect);
  38008. engine.setState(false);
  38009. // Texture
  38010. currentEffect.setTexture("textureSampler", this.texture);
  38011. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  38012. // Color
  38013. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  38014. // Scale / offset
  38015. currentEffect.setVector2("offset", this.offset);
  38016. currentEffect.setVector2("scale", this.scale);
  38017. // VBOs
  38018. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38019. // Draw order
  38020. if (!this.alphaTest) {
  38021. engine.setAlphaMode(this.alphaBlendingMode);
  38022. engine.draw(true, 0, 6);
  38023. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38024. }
  38025. else {
  38026. engine.draw(true, 0, 6);
  38027. }
  38028. this.onAfterRenderObservable.notifyObservers(this);
  38029. };
  38030. Layer.prototype.dispose = function () {
  38031. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38032. if (vertexBuffer) {
  38033. vertexBuffer.dispose();
  38034. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38035. }
  38036. if (this._indexBuffer) {
  38037. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38038. this._indexBuffer = null;
  38039. }
  38040. if (this.texture) {
  38041. this.texture.dispose();
  38042. this.texture = null;
  38043. }
  38044. // Remove from scene
  38045. var index = this._scene.layers.indexOf(this);
  38046. this._scene.layers.splice(index, 1);
  38047. // Callback
  38048. this.onDisposeObservable.notifyObservers(this);
  38049. this.onDisposeObservable.clear();
  38050. this.onAfterRenderObservable.clear();
  38051. this.onBeforeRenderObservable.clear();
  38052. };
  38053. return Layer;
  38054. }());
  38055. BABYLON.Layer = Layer;
  38056. })(BABYLON || (BABYLON = {}));
  38057. //# sourceMappingURL=babylon.layer.js.map
  38058. var BABYLON;
  38059. (function (BABYLON) {
  38060. var BlurPostProcess = (function (_super) {
  38061. __extends(BlurPostProcess, _super);
  38062. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  38063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38064. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38065. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  38066. _this.direction = direction;
  38067. _this._packedFloat = false;
  38068. _this.onApplyObservable.add(function (effect) {
  38069. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  38070. });
  38071. _this.kernel = kernel;
  38072. return _this;
  38073. }
  38074. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  38075. /**
  38076. * Gets the length in pixels of the blur sample region
  38077. */
  38078. get: function () {
  38079. return this._idealKernel;
  38080. },
  38081. /**
  38082. * Sets the length in pixels of the blur sample region
  38083. */
  38084. set: function (v) {
  38085. if (this._idealKernel === v) {
  38086. return;
  38087. }
  38088. v = Math.max(v, 1);
  38089. this._idealKernel = v;
  38090. this._kernel = this._nearestBestKernel(v);
  38091. this._updateParameters();
  38092. },
  38093. enumerable: true,
  38094. configurable: true
  38095. });
  38096. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  38097. /**
  38098. * Gets wether or not the blur is unpacking/repacking floats
  38099. */
  38100. get: function () {
  38101. return this._packedFloat;
  38102. },
  38103. /**
  38104. * Sets wether or not the blur needs to unpack/repack floats
  38105. */
  38106. set: function (v) {
  38107. if (this._packedFloat === v) {
  38108. return;
  38109. }
  38110. this._packedFloat = v;
  38111. this._updateParameters();
  38112. },
  38113. enumerable: true,
  38114. configurable: true
  38115. });
  38116. BlurPostProcess.prototype._updateParameters = function () {
  38117. // Generate sampling offsets and weights
  38118. var N = this._kernel;
  38119. var centerIndex = (N - 1) / 2;
  38120. // Generate Gaussian sampling weights over kernel
  38121. var offsets = [];
  38122. var weights = [];
  38123. var totalWeight = 0;
  38124. for (var i = 0; i < N; i++) {
  38125. var u = i / (N - 1);
  38126. var w = this._gaussianWeight(u * 2.0 - 1);
  38127. offsets[i] = (i - centerIndex);
  38128. weights[i] = w;
  38129. totalWeight += w;
  38130. }
  38131. // Normalize weights
  38132. for (var i = 0; i < weights.length; i++) {
  38133. weights[i] /= totalWeight;
  38134. }
  38135. // Optimize: combine samples to take advantage of hardware linear sampling
  38136. // Walk from left to center, combining pairs (symmetrically)
  38137. var linearSamplingWeights = [];
  38138. var linearSamplingOffsets = [];
  38139. var linearSamplingMap = [];
  38140. for (var i = 0; i <= centerIndex; i += 2) {
  38141. var j = Math.min(i + 1, Math.floor(centerIndex));
  38142. var singleCenterSample = i === j;
  38143. if (singleCenterSample) {
  38144. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38145. }
  38146. else {
  38147. var sharedCell = j === centerIndex;
  38148. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  38149. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  38150. if (offsetLinear === 0) {
  38151. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38152. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  38153. }
  38154. else {
  38155. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  38156. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  38157. }
  38158. }
  38159. }
  38160. for (var i = 0; i < linearSamplingMap.length; i++) {
  38161. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  38162. linearSamplingWeights[i] = linearSamplingMap[i].w;
  38163. }
  38164. // Replace with optimized
  38165. offsets = linearSamplingOffsets;
  38166. weights = linearSamplingWeights;
  38167. // Generate shaders
  38168. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  38169. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  38170. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  38171. var defines = "";
  38172. for (var i = 0; i < varyingCount; i++) {
  38173. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  38174. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  38175. }
  38176. var depCount = 0;
  38177. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  38178. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  38179. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  38180. depCount++;
  38181. }
  38182. if (this.packedFloat) {
  38183. defines += "#define PACKEDFLOAT 1";
  38184. }
  38185. this.updateEffect(defines, null, null, {
  38186. varyingCount: varyingCount,
  38187. depCount: depCount
  38188. });
  38189. };
  38190. /**
  38191. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  38192. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  38193. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  38194. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  38195. * The gaps between physical kernels are compensated for in the weighting of the samples
  38196. * @param idealKernel Ideal blur kernel.
  38197. * @return Nearest best kernel.
  38198. */
  38199. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  38200. var v = Math.round(idealKernel);
  38201. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  38202. var k = _a[_i];
  38203. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  38204. return Math.max(k, 3);
  38205. }
  38206. }
  38207. return Math.max(v, 3);
  38208. };
  38209. /**
  38210. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  38211. * @param x The point on the Gaussian distribution to sample.
  38212. * @return the value of the Gaussian function at x.
  38213. */
  38214. BlurPostProcess.prototype._gaussianWeight = function (x) {
  38215. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  38216. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  38217. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  38218. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  38219. // truncated at around 1.3% of peak strength.
  38220. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  38221. var sigma = (1 / 3);
  38222. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  38223. var exponent = -((x * x) / (2.0 * sigma * sigma));
  38224. var weight = (1.0 / denominator) * Math.exp(exponent);
  38225. return weight;
  38226. };
  38227. /**
  38228. * Generates a string that can be used as a floating point number in GLSL.
  38229. * @param x Value to print.
  38230. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  38231. * @return GLSL float string.
  38232. */
  38233. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  38234. if (decimalFigures === void 0) { decimalFigures = 8; }
  38235. return x.toFixed(decimalFigures).replace(/0+$/, '');
  38236. };
  38237. return BlurPostProcess;
  38238. }(BABYLON.PostProcess));
  38239. BABYLON.BlurPostProcess = BlurPostProcess;
  38240. })(BABYLON || (BABYLON = {}));
  38241. //# sourceMappingURL=babylon.blurPostProcess.js.map
  38242. var BABYLON;
  38243. (function (BABYLON) {
  38244. var FxaaPostProcess = (function (_super) {
  38245. __extends(FxaaPostProcess, _super);
  38246. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38247. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38248. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  38249. _this.onApplyObservable.add(function (effect) {
  38250. var texelSize = _this.texelSize;
  38251. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  38252. });
  38253. return _this;
  38254. }
  38255. return FxaaPostProcess;
  38256. }(BABYLON.PostProcess));
  38257. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38258. })(BABYLON || (BABYLON = {}));
  38259. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  38260. var BABYLON;
  38261. (function (BABYLON) {
  38262. var HighlightsPostProcess = (function (_super) {
  38263. __extends(HighlightsPostProcess, _super);
  38264. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38265. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38266. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  38267. }
  38268. return HighlightsPostProcess;
  38269. }(BABYLON.PostProcess));
  38270. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  38271. })(BABYLON || (BABYLON = {}));
  38272. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  38273. var BABYLON;
  38274. (function (BABYLON) {
  38275. var ImageProcessingPostProcess = (function (_super) {
  38276. __extends(ImageProcessingPostProcess, _super);
  38277. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38278. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38279. var _this = _super.call(this, name, "imageProcessing", [
  38280. 'contrast',
  38281. 'vignetteSettings1',
  38282. 'vignetteSettings2',
  38283. 'cameraExposureLinear',
  38284. 'vCameraColorCurveNegative',
  38285. 'vCameraColorCurveNeutral',
  38286. 'vCameraColorCurvePositive',
  38287. 'colorTransformSettings'
  38288. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  38289. _this.colorGradingWeight = 1.0;
  38290. _this.colorCurves = new BABYLON.ColorCurves();
  38291. _this._colorCurvesEnabled = true;
  38292. _this.cameraFov = 0.5;
  38293. _this.vignetteStretch = 0;
  38294. _this.vignetteCentreX = 0;
  38295. _this.vignetteCentreY = 0;
  38296. _this.vignetteWeight = 1.5;
  38297. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  38298. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  38299. _this._vignetteEnabled = true;
  38300. _this.cameraContrast = 1.0;
  38301. _this.cameraExposure = 1.68;
  38302. _this._cameraToneMappingEnabled = true;
  38303. _this._fromLinearSpace = false;
  38304. _this._updateParameters();
  38305. _this.onApply = function (effect) {
  38306. var aspectRatio = _this.aspectRatio;
  38307. // Color
  38308. if (_this._colorCurvesEnabled) {
  38309. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  38310. }
  38311. if (_this._vignetteEnabled) {
  38312. // Vignette
  38313. var vignetteScaleY = Math.tan(_this.cameraFov * 0.5);
  38314. var vignetteScaleX = vignetteScaleY * aspectRatio;
  38315. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  38316. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  38317. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  38318. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  38319. var vignettePower = -2.0 * _this.vignetteWeight;
  38320. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  38321. }
  38322. // Contrast and exposure
  38323. effect.setFloat('contrast', _this.cameraContrast);
  38324. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposure) * Math.PI);
  38325. // Color transform settings
  38326. if (_this._colorGradingTexture) {
  38327. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  38328. var textureSize = _this.colorGradingTexture.getSize().height;
  38329. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  38330. 0.5 / textureSize, // textureOffset
  38331. textureSize, // textureSize
  38332. _this.colorGradingWeight // weight
  38333. );
  38334. }
  38335. };
  38336. return _this;
  38337. }
  38338. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  38339. get: function () {
  38340. return this._colorGradingTexture;
  38341. },
  38342. set: function (value) {
  38343. if (this._colorGradingTexture === value) {
  38344. return;
  38345. }
  38346. this._colorGradingTexture = value;
  38347. this._updateParameters();
  38348. },
  38349. enumerable: true,
  38350. configurable: true
  38351. });
  38352. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  38353. get: function () {
  38354. return this._vignetteBlendMode;
  38355. },
  38356. set: function (value) {
  38357. if (this._vignetteBlendMode === value) {
  38358. return;
  38359. }
  38360. this._vignetteBlendMode = value;
  38361. this._updateParameters();
  38362. },
  38363. enumerable: true,
  38364. configurable: true
  38365. });
  38366. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  38367. get: function () {
  38368. return this._colorCurvesEnabled;
  38369. },
  38370. set: function (value) {
  38371. if (this._colorCurvesEnabled === value) {
  38372. return;
  38373. }
  38374. this._colorCurvesEnabled = value;
  38375. this._updateParameters();
  38376. },
  38377. enumerable: true,
  38378. configurable: true
  38379. });
  38380. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  38381. get: function () {
  38382. return this._vignetteEnabled;
  38383. },
  38384. set: function (value) {
  38385. if (this._vignetteEnabled === value) {
  38386. return;
  38387. }
  38388. this._vignetteEnabled = value;
  38389. this._updateParameters();
  38390. },
  38391. enumerable: true,
  38392. configurable: true
  38393. });
  38394. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  38395. get: function () {
  38396. return this._fromLinearSpace;
  38397. },
  38398. set: function (value) {
  38399. if (this._fromLinearSpace === value) {
  38400. return;
  38401. }
  38402. this._fromLinearSpace = value;
  38403. this._updateParameters();
  38404. },
  38405. enumerable: true,
  38406. configurable: true
  38407. });
  38408. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  38409. get: function () {
  38410. return this._cameraToneMappingEnabled;
  38411. },
  38412. set: function (value) {
  38413. if (this._cameraToneMappingEnabled === value) {
  38414. return;
  38415. }
  38416. this._cameraToneMappingEnabled = value;
  38417. this._updateParameters();
  38418. },
  38419. enumerable: true,
  38420. configurable: true
  38421. });
  38422. ImageProcessingPostProcess.prototype._updateParameters = function () {
  38423. var defines = "";
  38424. var samplers = ["textureSampler"];
  38425. if (this.colorGradingTexture) {
  38426. defines = "#define COLORGRADING\r\n";
  38427. samplers.push("txColorTransform");
  38428. }
  38429. if (this._vignetteEnabled) {
  38430. defines += "#define VIGNETTE\r\n";
  38431. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  38432. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  38433. }
  38434. else {
  38435. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  38436. }
  38437. }
  38438. if (this.cameraToneMappingEnabled) {
  38439. defines += "#define TONEMAPPING\r\n";
  38440. }
  38441. if (this._colorCurvesEnabled && this.colorCurves) {
  38442. defines += "#define COLORCURVES\r\n";
  38443. }
  38444. if (this._fromLinearSpace) {
  38445. defines += "#define FROMLINEARSPACE\r\n";
  38446. }
  38447. this.updateEffect(defines, null, samplers);
  38448. };
  38449. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  38450. get: function () {
  38451. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  38452. },
  38453. enumerable: true,
  38454. configurable: true
  38455. });
  38456. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  38457. get: function () {
  38458. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  38459. },
  38460. enumerable: true,
  38461. configurable: true
  38462. });
  38463. return ImageProcessingPostProcess;
  38464. }(BABYLON.PostProcess));
  38465. // Statics
  38466. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  38467. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  38468. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  38469. })(BABYLON || (BABYLON = {}));
  38470. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  38471. var BABYLON;
  38472. (function (BABYLON) {
  38473. /**
  38474. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38475. * It can help converting any input color in a desired output one. This can then be used to create effects
  38476. * from sepia, black and white to sixties or futuristic rendering...
  38477. *
  38478. * The only supported format is currently 3dl.
  38479. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38480. */
  38481. var ColorGradingTexture = (function (_super) {
  38482. __extends(ColorGradingTexture, _super);
  38483. /**
  38484. * Instantiates a ColorGradingTexture from the following parameters.
  38485. *
  38486. * @param url The location of the color gradind data (currently only supporting 3dl)
  38487. * @param scene The scene the texture will be used in
  38488. */
  38489. function ColorGradingTexture(url, scene) {
  38490. var _this = _super.call(this, scene) || this;
  38491. if (!url) {
  38492. return _this;
  38493. }
  38494. _this._textureMatrix = BABYLON.Matrix.Identity();
  38495. _this.name = url;
  38496. _this.url = url;
  38497. _this.hasAlpha = false;
  38498. _this.isCube = false;
  38499. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38500. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38501. _this.anisotropicFilteringLevel = 1;
  38502. _this._texture = _this._getFromCache(url, true);
  38503. if (!_this._texture) {
  38504. if (!scene.useDelayedTextureLoading) {
  38505. _this.loadTexture();
  38506. }
  38507. else {
  38508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38509. }
  38510. }
  38511. return _this;
  38512. }
  38513. /**
  38514. * Returns the texture matrix used in most of the material.
  38515. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38516. */
  38517. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38518. return this._textureMatrix;
  38519. };
  38520. /**
  38521. * Occurs when the file being loaded is a .3dl LUT file.
  38522. */
  38523. ColorGradingTexture.prototype.load3dlTexture = function () {
  38524. var _this = this;
  38525. var mipLevels = 0;
  38526. var floatArrayView = null;
  38527. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38528. this._texture = texture;
  38529. var callback = function (text) {
  38530. var data;
  38531. var tempData;
  38532. var line;
  38533. var lines = text.split('\n');
  38534. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38535. var maxColor = 0;
  38536. for (var i = 0; i < lines.length; i++) {
  38537. line = lines[i];
  38538. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38539. continue;
  38540. if (line.indexOf('#') === 0)
  38541. continue;
  38542. var words = line.split(" ");
  38543. if (size === 0) {
  38544. // Number of space + one
  38545. size = words.length;
  38546. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38547. tempData = new Float32Array(size * size * size * 4);
  38548. continue;
  38549. }
  38550. if (size != 0) {
  38551. var r = Math.max(parseInt(words[0]), 0);
  38552. var g = Math.max(parseInt(words[1]), 0);
  38553. var b = Math.max(parseInt(words[2]), 0);
  38554. maxColor = Math.max(r, maxColor);
  38555. maxColor = Math.max(g, maxColor);
  38556. maxColor = Math.max(b, maxColor);
  38557. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38558. tempData[pixelStorageIndex + 0] = r;
  38559. tempData[pixelStorageIndex + 1] = g;
  38560. tempData[pixelStorageIndex + 2] = b;
  38561. tempData[pixelStorageIndex + 3] = 0;
  38562. pixelIndexSlice++;
  38563. if (pixelIndexSlice % size == 0) {
  38564. pixelIndexH++;
  38565. pixelIndexSlice = 0;
  38566. if (pixelIndexH % size == 0) {
  38567. pixelIndexW++;
  38568. pixelIndexH = 0;
  38569. }
  38570. }
  38571. }
  38572. }
  38573. for (var i = 0; i < tempData.length; i++) {
  38574. var value = tempData[i];
  38575. data[i] = (value / maxColor * 255);
  38576. }
  38577. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  38578. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38579. };
  38580. BABYLON.Tools.LoadFile(this.url, callback);
  38581. return this._texture;
  38582. };
  38583. /**
  38584. * Starts the loading process of the texture.
  38585. */
  38586. ColorGradingTexture.prototype.loadTexture = function () {
  38587. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38588. this.load3dlTexture();
  38589. }
  38590. };
  38591. /**
  38592. * Clones the color gradind texture.
  38593. */
  38594. ColorGradingTexture.prototype.clone = function () {
  38595. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38596. // Base texture
  38597. newTexture.level = this.level;
  38598. return newTexture;
  38599. };
  38600. /**
  38601. * Called during delayed load for textures.
  38602. */
  38603. ColorGradingTexture.prototype.delayLoad = function () {
  38604. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38605. return;
  38606. }
  38607. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38608. this._texture = this._getFromCache(this.url, true);
  38609. if (!this._texture) {
  38610. this.loadTexture();
  38611. }
  38612. };
  38613. /**
  38614. * Binds the color grading to the shader.
  38615. * @param colorGrading The texture to bind
  38616. * @param effect The effect to bind to
  38617. */
  38618. ColorGradingTexture.Bind = function (colorGrading, effect) {
  38619. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  38620. var x = colorGrading.level; // Texture Level
  38621. var y = colorGrading.getSize().height; // Texture Size example with 8
  38622. var z = y - 1.0; // SizeMinusOne 8 - 1
  38623. var w = 1 / y; // Space of 1 slice 1 / 8
  38624. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  38625. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  38626. 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
  38627. 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
  38628. 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
  38629. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  38630. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  38631. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  38632. };
  38633. /**
  38634. * Prepare the list of uniforms associated with the ColorGrading effects.
  38635. * @param uniformsList The list of uniforms used in the effect
  38636. * @param samplersList The list of samplers used in the effect
  38637. */
  38638. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  38639. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  38640. samplersList.push("cameraColorGrading2DSampler");
  38641. };
  38642. /**
  38643. * Parses a color grading texture serialized by Babylon.
  38644. * @param parsedTexture The texture information being parsedTexture
  38645. * @param scene The scene to load the texture in
  38646. * @param rootUrl The root url of the data assets to load
  38647. * @return A color gradind texture
  38648. */
  38649. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38650. var texture = null;
  38651. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38652. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  38653. texture.name = parsedTexture.name;
  38654. texture.level = parsedTexture.level;
  38655. }
  38656. return texture;
  38657. };
  38658. /**
  38659. * Serializes the LUT texture to json format.
  38660. */
  38661. ColorGradingTexture.prototype.serialize = function () {
  38662. if (!this.name) {
  38663. return null;
  38664. }
  38665. var serializationObject = {};
  38666. serializationObject.name = this.name;
  38667. serializationObject.level = this.level;
  38668. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38669. return serializationObject;
  38670. };
  38671. return ColorGradingTexture;
  38672. }(BABYLON.BaseTexture));
  38673. /**
  38674. * Empty line regex stored for GC.
  38675. */
  38676. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38677. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38678. })(BABYLON || (BABYLON = {}));
  38679. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38680. var BABYLON;
  38681. (function (BABYLON) {
  38682. /**
  38683. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38684. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38685. * 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;
  38686. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38687. */
  38688. var ColorCurves = (function () {
  38689. function ColorCurves() {
  38690. this._dirty = true;
  38691. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38692. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38693. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38694. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38695. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38696. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38697. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38698. this._globalHue = 30;
  38699. this._globalDensity = 0;
  38700. this._globalSaturation = 0;
  38701. this._globalExposure = 0;
  38702. this._highlightsHue = 30;
  38703. this._highlightsDensity = 0;
  38704. this._highlightsSaturation = 0;
  38705. this._highlightsExposure = 0;
  38706. this._midtonesHue = 30;
  38707. this._midtonesDensity = 0;
  38708. this._midtonesSaturation = 0;
  38709. this._midtonesExposure = 0;
  38710. this._shadowsHue = 30;
  38711. this._shadowsDensity = 0;
  38712. this._shadowsSaturation = 0;
  38713. this._shadowsExposure = 0;
  38714. }
  38715. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38716. /**
  38717. * Gets the global Hue value.
  38718. * 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).
  38719. */
  38720. get: function () {
  38721. return this._globalHue;
  38722. },
  38723. /**
  38724. * Sets the global Hue value.
  38725. * 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).
  38726. */
  38727. set: function (value) {
  38728. this._globalHue = value;
  38729. this._dirty = true;
  38730. },
  38731. enumerable: true,
  38732. configurable: true
  38733. });
  38734. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38735. /**
  38736. * Gets the global Density value.
  38737. * 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.
  38738. * Values less than zero provide a filter of opposite hue.
  38739. */
  38740. get: function () {
  38741. return this._globalDensity;
  38742. },
  38743. /**
  38744. * Sets the global Density value.
  38745. * 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.
  38746. * Values less than zero provide a filter of opposite hue.
  38747. */
  38748. set: function (value) {
  38749. this._globalDensity = value;
  38750. this._dirty = true;
  38751. },
  38752. enumerable: true,
  38753. configurable: true
  38754. });
  38755. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38756. /**
  38757. * Gets the global Saturation value.
  38758. * 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.
  38759. */
  38760. get: function () {
  38761. return this._globalSaturation;
  38762. },
  38763. /**
  38764. * Sets the global Saturation value.
  38765. * 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.
  38766. */
  38767. set: function (value) {
  38768. this._globalSaturation = value;
  38769. this._dirty = true;
  38770. },
  38771. enumerable: true,
  38772. configurable: true
  38773. });
  38774. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38775. /**
  38776. * Gets the highlights Hue value.
  38777. * 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).
  38778. */
  38779. get: function () {
  38780. return this._highlightsHue;
  38781. },
  38782. /**
  38783. * Sets the highlights Hue value.
  38784. * 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).
  38785. */
  38786. set: function (value) {
  38787. this._highlightsHue = value;
  38788. this._dirty = true;
  38789. },
  38790. enumerable: true,
  38791. configurable: true
  38792. });
  38793. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38794. /**
  38795. * Gets the highlights Density value.
  38796. * 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.
  38797. * Values less than zero provide a filter of opposite hue.
  38798. */
  38799. get: function () {
  38800. return this._highlightsDensity;
  38801. },
  38802. /**
  38803. * Sets the highlights Density value.
  38804. * 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.
  38805. * Values less than zero provide a filter of opposite hue.
  38806. */
  38807. set: function (value) {
  38808. this._highlightsDensity = value;
  38809. this._dirty = true;
  38810. },
  38811. enumerable: true,
  38812. configurable: true
  38813. });
  38814. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38815. /**
  38816. * Gets the highlights Saturation value.
  38817. * 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.
  38818. */
  38819. get: function () {
  38820. return this._highlightsSaturation;
  38821. },
  38822. /**
  38823. * Sets the highlights Saturation value.
  38824. * 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.
  38825. */
  38826. set: function (value) {
  38827. this._highlightsSaturation = value;
  38828. this._dirty = true;
  38829. },
  38830. enumerable: true,
  38831. configurable: true
  38832. });
  38833. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38834. /**
  38835. * Gets the highlights Exposure value.
  38836. * 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.
  38837. */
  38838. get: function () {
  38839. return this._highlightsExposure;
  38840. },
  38841. /**
  38842. * Sets the highlights Exposure value.
  38843. * 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.
  38844. */
  38845. set: function (value) {
  38846. this._highlightsExposure = value;
  38847. this._dirty = true;
  38848. },
  38849. enumerable: true,
  38850. configurable: true
  38851. });
  38852. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38853. /**
  38854. * Gets the midtones Hue value.
  38855. * 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).
  38856. */
  38857. get: function () {
  38858. return this._midtonesHue;
  38859. },
  38860. /**
  38861. * Sets the midtones Hue value.
  38862. * 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).
  38863. */
  38864. set: function (value) {
  38865. this._midtonesHue = value;
  38866. this._dirty = true;
  38867. },
  38868. enumerable: true,
  38869. configurable: true
  38870. });
  38871. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38872. /**
  38873. * Gets the midtones Density value.
  38874. * 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.
  38875. * Values less than zero provide a filter of opposite hue.
  38876. */
  38877. get: function () {
  38878. return this._midtonesDensity;
  38879. },
  38880. /**
  38881. * Sets the midtones Density value.
  38882. * 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.
  38883. * Values less than zero provide a filter of opposite hue.
  38884. */
  38885. set: function (value) {
  38886. this._midtonesDensity = value;
  38887. this._dirty = true;
  38888. },
  38889. enumerable: true,
  38890. configurable: true
  38891. });
  38892. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38893. /**
  38894. * Gets the midtones Saturation value.
  38895. * 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.
  38896. */
  38897. get: function () {
  38898. return this._midtonesSaturation;
  38899. },
  38900. /**
  38901. * Sets the midtones Saturation value.
  38902. * 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.
  38903. */
  38904. set: function (value) {
  38905. this._midtonesSaturation = value;
  38906. this._dirty = true;
  38907. },
  38908. enumerable: true,
  38909. configurable: true
  38910. });
  38911. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38912. /**
  38913. * Gets the midtones Exposure value.
  38914. * 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.
  38915. */
  38916. get: function () {
  38917. return this._midtonesExposure;
  38918. },
  38919. /**
  38920. * Sets the midtones Exposure value.
  38921. * 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.
  38922. */
  38923. set: function (value) {
  38924. this._midtonesExposure = value;
  38925. this._dirty = true;
  38926. },
  38927. enumerable: true,
  38928. configurable: true
  38929. });
  38930. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38931. /**
  38932. * Gets the shadows Hue value.
  38933. * 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).
  38934. */
  38935. get: function () {
  38936. return this._shadowsHue;
  38937. },
  38938. /**
  38939. * Sets the shadows Hue value.
  38940. * 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).
  38941. */
  38942. set: function (value) {
  38943. this._shadowsHue = value;
  38944. this._dirty = true;
  38945. },
  38946. enumerable: true,
  38947. configurable: true
  38948. });
  38949. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38950. /**
  38951. * Gets the shadows Density value.
  38952. * 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.
  38953. * Values less than zero provide a filter of opposite hue.
  38954. */
  38955. get: function () {
  38956. return this._shadowsDensity;
  38957. },
  38958. /**
  38959. * Sets the shadows Density value.
  38960. * 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.
  38961. * Values less than zero provide a filter of opposite hue.
  38962. */
  38963. set: function (value) {
  38964. this._shadowsDensity = value;
  38965. this._dirty = true;
  38966. },
  38967. enumerable: true,
  38968. configurable: true
  38969. });
  38970. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38971. /**
  38972. * Gets the shadows Saturation value.
  38973. * 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.
  38974. */
  38975. get: function () {
  38976. return this._shadowsSaturation;
  38977. },
  38978. /**
  38979. * Sets the shadows Saturation value.
  38980. * 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.
  38981. */
  38982. set: function (value) {
  38983. this._shadowsSaturation = value;
  38984. this._dirty = true;
  38985. },
  38986. enumerable: true,
  38987. configurable: true
  38988. });
  38989. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38990. /**
  38991. * Gets the shadows Exposure value.
  38992. * 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.
  38993. */
  38994. get: function () {
  38995. return this._shadowsExposure;
  38996. },
  38997. /**
  38998. * Sets the shadows Exposure value.
  38999. * 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.
  39000. */
  39001. set: function (value) {
  39002. this._shadowsExposure = value;
  39003. this._dirty = true;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. /**
  39009. * Binds the color curves to the shader.
  39010. * @param colorCurves The color curve to bind
  39011. * @param effect The effect to bind to
  39012. */
  39013. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  39014. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  39015. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  39016. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  39017. if (colorCurves._dirty) {
  39018. colorCurves._dirty = false;
  39019. // Fill in global info.
  39020. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  39021. // Compute highlights info.
  39022. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  39023. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  39024. // Compute midtones info.
  39025. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  39026. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  39027. // Compute shadows info.
  39028. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  39029. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  39030. // Compute deltas (neutral is midtones).
  39031. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  39032. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  39033. }
  39034. if (effect) {
  39035. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  39036. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  39037. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  39038. }
  39039. };
  39040. /**
  39041. * Prepare the list of uniforms associated with the ColorCurves effects.
  39042. * @param uniformsList The list of uniforms used in the effect
  39043. */
  39044. ColorCurves.PrepareUniforms = function (uniformsList) {
  39045. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  39046. };
  39047. /**
  39048. * Returns color grading data based on a hue, density, saturation and exposure value.
  39049. * @param filterHue The hue of the color filter.
  39050. * @param filterDensity The density of the color filter.
  39051. * @param saturation The saturation.
  39052. * @param exposure The exposure.
  39053. * @param result The result data container.
  39054. */
  39055. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  39056. if (hue == null) {
  39057. return;
  39058. }
  39059. hue = ColorCurves.clamp(hue, 0, 360);
  39060. density = ColorCurves.clamp(density, -100, 100);
  39061. saturation = ColorCurves.clamp(saturation, -100, 100);
  39062. exposure = ColorCurves.clamp(exposure, -100, 100);
  39063. // Remap the slider/config filter density with non-linear mapping and also scale by half
  39064. // so that the maximum filter density is only 50% control. This provides fine control
  39065. // for small values and reasonable range.
  39066. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  39067. density *= 0.5;
  39068. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  39069. if (density < 0) {
  39070. density *= -1;
  39071. hue = (hue + 180) % 360;
  39072. }
  39073. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  39074. result.scaleToRef(2, result);
  39075. result.a = 1 + 0.01 * saturation;
  39076. };
  39077. /**
  39078. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  39079. * @param value The input slider value in range [-100,100].
  39080. * @returns Adjusted value.
  39081. */
  39082. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  39083. value /= 100;
  39084. var x = Math.abs(value);
  39085. x = Math.pow(x, 2);
  39086. if (value < 0) {
  39087. x *= -1;
  39088. }
  39089. x *= 100;
  39090. return x;
  39091. };
  39092. /**
  39093. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  39094. * @param hue The hue (H) input.
  39095. * @param saturation The saturation (S) input.
  39096. * @param brightness The brightness (B) input.
  39097. * @result An RGBA color represented as Vector4.
  39098. */
  39099. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  39100. var h = ColorCurves.clamp(hue, 0, 360);
  39101. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  39102. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  39103. if (s === 0) {
  39104. result.r = v;
  39105. result.g = v;
  39106. result.b = v;
  39107. }
  39108. else {
  39109. // sector 0 to 5
  39110. h /= 60;
  39111. var i = Math.floor(h);
  39112. // fractional part of h
  39113. var f = h - i;
  39114. var p = v * (1 - s);
  39115. var q = v * (1 - s * f);
  39116. var t = v * (1 - s * (1 - f));
  39117. switch (i) {
  39118. case 0:
  39119. result.r = v;
  39120. result.g = t;
  39121. result.b = p;
  39122. break;
  39123. case 1:
  39124. result.r = q;
  39125. result.g = v;
  39126. result.b = p;
  39127. break;
  39128. case 2:
  39129. result.r = p;
  39130. result.g = v;
  39131. result.b = t;
  39132. break;
  39133. case 3:
  39134. result.r = p;
  39135. result.g = q;
  39136. result.b = v;
  39137. break;
  39138. case 4:
  39139. result.r = t;
  39140. result.g = p;
  39141. result.b = v;
  39142. break;
  39143. default:
  39144. result.r = v;
  39145. result.g = p;
  39146. result.b = q;
  39147. break;
  39148. }
  39149. }
  39150. result.a = 1;
  39151. };
  39152. /**
  39153. * Returns a value clamped between min and max
  39154. * @param value The value to clamp
  39155. * @param min The minimum of value
  39156. * @param max The maximum of value
  39157. * @returns The clamped value.
  39158. */
  39159. ColorCurves.clamp = function (value, min, max) {
  39160. return Math.min(Math.max(value, min), max);
  39161. };
  39162. /**
  39163. * Clones the current color curve instance.
  39164. * @return The cloned curves
  39165. */
  39166. ColorCurves.prototype.clone = function () {
  39167. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39168. };
  39169. /**
  39170. * Serializes the current color curve instance to a json representation.
  39171. * @return a JSON representation
  39172. */
  39173. ColorCurves.prototype.serialize = function () {
  39174. return BABYLON.SerializationHelper.Serialize(this);
  39175. };
  39176. /**
  39177. * Parses the color curve from a json representation.
  39178. * @param source the JSON source to parse
  39179. * @return The parsed curves
  39180. */
  39181. ColorCurves.Parse = function (source) {
  39182. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39183. };
  39184. return ColorCurves;
  39185. }());
  39186. __decorate([
  39187. BABYLON.serialize()
  39188. ], ColorCurves.prototype, "_globalHue", void 0);
  39189. __decorate([
  39190. BABYLON.serialize()
  39191. ], ColorCurves.prototype, "_globalDensity", void 0);
  39192. __decorate([
  39193. BABYLON.serialize()
  39194. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39195. __decorate([
  39196. BABYLON.serialize()
  39197. ], ColorCurves.prototype, "_globalExposure", void 0);
  39198. __decorate([
  39199. BABYLON.serialize()
  39200. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39201. __decorate([
  39202. BABYLON.serialize()
  39203. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39204. __decorate([
  39205. BABYLON.serialize()
  39206. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39207. __decorate([
  39208. BABYLON.serialize()
  39209. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39210. __decorate([
  39211. BABYLON.serialize()
  39212. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39213. __decorate([
  39214. BABYLON.serialize()
  39215. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39216. __decorate([
  39217. BABYLON.serialize()
  39218. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39219. __decorate([
  39220. BABYLON.serialize()
  39221. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39222. BABYLON.ColorCurves = ColorCurves;
  39223. })(BABYLON || (BABYLON = {}));
  39224. //# sourceMappingURL=babylon.colorCurves.js.map
  39225. var BABYLON;
  39226. (function (BABYLON) {
  39227. var PostProcessRenderPipelineManager = (function () {
  39228. function PostProcessRenderPipelineManager() {
  39229. this._renderPipelines = {};
  39230. }
  39231. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39232. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39233. };
  39234. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39235. var renderPipeline = this._renderPipelines[renderPipelineName];
  39236. if (!renderPipeline) {
  39237. return;
  39238. }
  39239. renderPipeline._attachCameras(cameras, unique);
  39240. };
  39241. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39242. var renderPipeline = this._renderPipelines[renderPipelineName];
  39243. if (!renderPipeline) {
  39244. return;
  39245. }
  39246. renderPipeline._detachCameras(cameras);
  39247. };
  39248. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39249. var renderPipeline = this._renderPipelines[renderPipelineName];
  39250. if (!renderPipeline) {
  39251. return;
  39252. }
  39253. renderPipeline._enableEffect(renderEffectName, cameras);
  39254. };
  39255. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39256. var renderPipeline = this._renderPipelines[renderPipelineName];
  39257. if (!renderPipeline) {
  39258. return;
  39259. }
  39260. renderPipeline._disableEffect(renderEffectName, cameras);
  39261. };
  39262. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39263. var renderPipeline = this._renderPipelines[renderPipelineName];
  39264. if (!renderPipeline) {
  39265. return;
  39266. }
  39267. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39268. };
  39269. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39270. var renderPipeline = this._renderPipelines[renderPipelineName];
  39271. if (!renderPipeline) {
  39272. return;
  39273. }
  39274. renderPipeline._disableDisplayOnlyPass(cameras);
  39275. };
  39276. PostProcessRenderPipelineManager.prototype.update = function () {
  39277. for (var renderPipelineName in this._renderPipelines) {
  39278. var pipeline = this._renderPipelines[renderPipelineName];
  39279. if (!pipeline.isSupported) {
  39280. pipeline.dispose();
  39281. delete this._renderPipelines[renderPipelineName];
  39282. }
  39283. else {
  39284. pipeline._update();
  39285. }
  39286. }
  39287. };
  39288. return PostProcessRenderPipelineManager;
  39289. }());
  39290. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39291. })(BABYLON || (BABYLON = {}));
  39292. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39293. var BABYLON;
  39294. (function (BABYLON) {
  39295. var PostProcessRenderPass = (function () {
  39296. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39297. this._enabled = true;
  39298. this._refCount = 0;
  39299. this._name = name;
  39300. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39301. this.setRenderList(renderList);
  39302. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39303. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39304. this._scene = scene;
  39305. this._renderList = renderList;
  39306. }
  39307. // private
  39308. PostProcessRenderPass.prototype._incRefCount = function () {
  39309. if (this._refCount === 0) {
  39310. this._scene.customRenderTargets.push(this._renderTexture);
  39311. }
  39312. return ++this._refCount;
  39313. };
  39314. PostProcessRenderPass.prototype._decRefCount = function () {
  39315. this._refCount--;
  39316. if (this._refCount <= 0) {
  39317. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39318. }
  39319. return this._refCount;
  39320. };
  39321. PostProcessRenderPass.prototype._update = function () {
  39322. this.setRenderList(this._renderList);
  39323. };
  39324. // public
  39325. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39326. this._renderTexture.renderList = renderList;
  39327. };
  39328. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39329. return this._renderTexture;
  39330. };
  39331. return PostProcessRenderPass;
  39332. }());
  39333. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39334. })(BABYLON || (BABYLON = {}));
  39335. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39336. var BABYLON;
  39337. (function (BABYLON) {
  39338. var PostProcessRenderEffect = (function () {
  39339. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39340. this._engine = engine;
  39341. this._name = name;
  39342. this._singleInstance = singleInstance || true;
  39343. this._getPostProcess = getPostProcess;
  39344. this._cameras = [];
  39345. this._indicesForCamera = [];
  39346. this._postProcesses = {};
  39347. this._renderPasses = {};
  39348. this._renderEffectAsPasses = {};
  39349. }
  39350. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39351. get: function () {
  39352. for (var index in this._postProcesses) {
  39353. if (!this._postProcesses[index].isSupported) {
  39354. return false;
  39355. }
  39356. }
  39357. return true;
  39358. },
  39359. enumerable: true,
  39360. configurable: true
  39361. });
  39362. PostProcessRenderEffect.prototype._update = function () {
  39363. for (var renderPassName in this._renderPasses) {
  39364. this._renderPasses[renderPassName]._update();
  39365. }
  39366. };
  39367. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39368. this._renderPasses[renderPass._name] = renderPass;
  39369. this._linkParameters();
  39370. };
  39371. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39372. delete this._renderPasses[renderPass._name];
  39373. this._linkParameters();
  39374. };
  39375. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39376. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39377. this._linkParameters();
  39378. };
  39379. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39380. for (var renderPassName in this._renderPasses) {
  39381. if (renderPassName === passName) {
  39382. return this._renderPasses[passName];
  39383. }
  39384. }
  39385. };
  39386. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39387. this._renderPasses = {};
  39388. this._linkParameters();
  39389. };
  39390. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39391. var cameraKey;
  39392. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39393. for (var i = 0; i < _cam.length; i++) {
  39394. var camera = _cam[i];
  39395. var cameraName = camera.name;
  39396. if (this._singleInstance) {
  39397. cameraKey = 0;
  39398. }
  39399. else {
  39400. cameraKey = cameraName;
  39401. }
  39402. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39403. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39404. if (!this._indicesForCamera[cameraName]) {
  39405. this._indicesForCamera[cameraName] = [];
  39406. }
  39407. this._indicesForCamera[cameraName].push(index);
  39408. if (this._cameras.indexOf(camera) === -1) {
  39409. this._cameras[cameraName] = camera;
  39410. }
  39411. for (var passName in this._renderPasses) {
  39412. this._renderPasses[passName]._incRefCount();
  39413. }
  39414. }
  39415. this._linkParameters();
  39416. };
  39417. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39418. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39419. for (var i = 0; i < _cam.length; i++) {
  39420. var camera = _cam[i];
  39421. var cameraName = camera.name;
  39422. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39423. var index = this._cameras.indexOf(cameraName);
  39424. this._indicesForCamera.splice(index, 1);
  39425. this._cameras.splice(index, 1);
  39426. for (var passName in this._renderPasses) {
  39427. this._renderPasses[passName]._decRefCount();
  39428. }
  39429. }
  39430. };
  39431. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39432. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39433. for (var i = 0; i < _cam.length; i++) {
  39434. var camera = _cam[i];
  39435. var cameraName = camera.name;
  39436. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39437. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39438. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39439. }
  39440. }
  39441. for (var passName in this._renderPasses) {
  39442. this._renderPasses[passName]._incRefCount();
  39443. }
  39444. }
  39445. };
  39446. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39447. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39448. for (var i = 0; i < _cam.length; i++) {
  39449. var camera = _cam[i];
  39450. var cameraName = camera.Name;
  39451. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39452. for (var passName in this._renderPasses) {
  39453. this._renderPasses[passName]._decRefCount();
  39454. }
  39455. }
  39456. };
  39457. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39458. if (this._singleInstance) {
  39459. return this._postProcesses[0];
  39460. }
  39461. else {
  39462. return this._postProcesses[camera.name];
  39463. }
  39464. };
  39465. PostProcessRenderEffect.prototype._linkParameters = function () {
  39466. var _this = this;
  39467. for (var index in this._postProcesses) {
  39468. if (this.applyParameters) {
  39469. this.applyParameters(this._postProcesses[index]);
  39470. }
  39471. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39472. _this._linkTextures(effect);
  39473. });
  39474. }
  39475. };
  39476. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39477. for (var renderPassName in this._renderPasses) {
  39478. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39479. }
  39480. for (var renderEffectName in this._renderEffectAsPasses) {
  39481. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39482. }
  39483. };
  39484. return PostProcessRenderEffect;
  39485. }());
  39486. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39487. })(BABYLON || (BABYLON = {}));
  39488. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39489. var BABYLON;
  39490. (function (BABYLON) {
  39491. var PostProcessRenderPipeline = (function () {
  39492. function PostProcessRenderPipeline(engine, name) {
  39493. this._engine = engine;
  39494. this._name = name;
  39495. this._renderEffects = new Array();
  39496. this._renderEffectsForIsolatedPass = new Array();
  39497. this._cameras = [];
  39498. }
  39499. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39500. get: function () {
  39501. for (var renderEffectName in this._renderEffects) {
  39502. if (!this._renderEffects[renderEffectName].isSupported) {
  39503. return false;
  39504. }
  39505. }
  39506. return true;
  39507. },
  39508. enumerable: true,
  39509. configurable: true
  39510. });
  39511. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39512. this._renderEffects[renderEffect._name] = renderEffect;
  39513. };
  39514. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39515. var renderEffects = this._renderEffects[renderEffectName];
  39516. if (!renderEffects) {
  39517. return;
  39518. }
  39519. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39520. };
  39521. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39522. var renderEffects = this._renderEffects[renderEffectName];
  39523. if (!renderEffects) {
  39524. return;
  39525. }
  39526. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39527. };
  39528. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39529. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39530. var indicesToDelete = [];
  39531. var i;
  39532. for (i = 0; i < _cam.length; i++) {
  39533. var camera = _cam[i];
  39534. var cameraName = camera.name;
  39535. if (this._cameras.indexOf(camera) === -1) {
  39536. this._cameras[cameraName] = camera;
  39537. }
  39538. else if (unique) {
  39539. indicesToDelete.push(i);
  39540. }
  39541. }
  39542. for (i = 0; i < indicesToDelete.length; i++) {
  39543. cameras.splice(indicesToDelete[i], 1);
  39544. }
  39545. for (var renderEffectName in this._renderEffects) {
  39546. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39547. }
  39548. };
  39549. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39550. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39551. for (var renderEffectName in this._renderEffects) {
  39552. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39553. }
  39554. for (var i = 0; i < _cam.length; i++) {
  39555. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39556. }
  39557. };
  39558. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39559. var _this = this;
  39560. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39561. var pass = null;
  39562. var renderEffectName;
  39563. for (renderEffectName in this._renderEffects) {
  39564. pass = this._renderEffects[renderEffectName].getPass(passName);
  39565. if (pass != null) {
  39566. break;
  39567. }
  39568. }
  39569. if (pass === null) {
  39570. return;
  39571. }
  39572. for (renderEffectName in this._renderEffects) {
  39573. this._renderEffects[renderEffectName]._disable(_cam);
  39574. }
  39575. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39576. for (var i = 0; i < _cam.length; i++) {
  39577. var camera = _cam[i];
  39578. var cameraName = camera.name;
  39579. 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); });
  39580. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39581. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39582. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39583. }
  39584. };
  39585. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39586. var _this = this;
  39587. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39588. for (var i = 0; i < _cam.length; i++) {
  39589. var camera = _cam[i];
  39590. var cameraName = camera.name;
  39591. 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); });
  39592. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39593. }
  39594. for (var renderEffectName in this._renderEffects) {
  39595. this._renderEffects[renderEffectName]._enable(_cam);
  39596. }
  39597. };
  39598. PostProcessRenderPipeline.prototype._update = function () {
  39599. for (var renderEffectName in this._renderEffects) {
  39600. this._renderEffects[renderEffectName]._update();
  39601. }
  39602. for (var i = 0; i < this._cameras.length; i++) {
  39603. var cameraName = this._cameras[i].name;
  39604. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39605. this._renderEffectsForIsolatedPass[cameraName]._update();
  39606. }
  39607. }
  39608. };
  39609. PostProcessRenderPipeline.prototype._reset = function () {
  39610. this._renderEffects = new Array();
  39611. this._renderEffectsForIsolatedPass = new Array();
  39612. };
  39613. PostProcessRenderPipeline.prototype.dispose = function () {
  39614. // Must be implemented by children
  39615. };
  39616. return PostProcessRenderPipeline;
  39617. }());
  39618. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39619. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39620. __decorate([
  39621. BABYLON.serialize()
  39622. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  39623. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39624. })(BABYLON || (BABYLON = {}));
  39625. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39626. var BABYLON;
  39627. (function (BABYLON) {
  39628. var DefaultRenderingPipeline = (function (_super) {
  39629. __extends(DefaultRenderingPipeline, _super);
  39630. /**
  39631. * @constructor
  39632. * @param {string} name - The rendering pipeline name
  39633. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39634. * @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)
  39635. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39636. */
  39637. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  39638. var _this = _super.call(this, scene.getEngine(), name) || this;
  39639. _this.PassPostProcessId = "PassPostProcessEffect";
  39640. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  39641. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  39642. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  39643. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  39644. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  39645. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  39646. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  39647. // IAnimatable
  39648. _this.animations = [];
  39649. // Values
  39650. _this._bloomEnabled = false;
  39651. _this._fxaaEnabled = false;
  39652. _this._imageProcessingEnabled = true;
  39653. _this._bloomScale = 0.6;
  39654. /**
  39655. * Specifies the size of the bloom blur kernel, relative to the final output size
  39656. */
  39657. _this.bloomKernel = 64;
  39658. /**
  39659. * Specifies the weight of the bloom in the final rendering
  39660. */
  39661. _this._bloomWeight = 0.15;
  39662. _this._cameras = cameras || [];
  39663. // Initialize
  39664. _this._scene = scene;
  39665. var caps = _this._scene.getEngine().getCaps();
  39666. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  39667. // Misc
  39668. if (_this._hdr) {
  39669. if (caps.textureHalfFloatRender) {
  39670. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  39671. }
  39672. else if (caps.textureFloatRender) {
  39673. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  39674. }
  39675. }
  39676. else {
  39677. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  39678. }
  39679. // Attach
  39680. scene.postProcessRenderPipelineManager.addPipeline(_this);
  39681. _this._buildPipeline();
  39682. return _this;
  39683. }
  39684. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  39685. get: function () {
  39686. return this._bloomWeight;
  39687. },
  39688. set: function (value) {
  39689. if (this._bloomWeight === value) {
  39690. return;
  39691. }
  39692. this._bloomWeight = value;
  39693. if (this._hdr && this.copyBack) {
  39694. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  39695. }
  39696. },
  39697. enumerable: true,
  39698. configurable: true
  39699. });
  39700. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  39701. get: function () {
  39702. return this._bloomScale;
  39703. },
  39704. set: function (value) {
  39705. if (this._bloomScale === value) {
  39706. return;
  39707. }
  39708. this._bloomScale = value;
  39709. this._buildPipeline();
  39710. },
  39711. enumerable: true,
  39712. configurable: true
  39713. });
  39714. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  39715. get: function () {
  39716. return this._bloomEnabled;
  39717. },
  39718. set: function (enabled) {
  39719. if (this._bloomEnabled === enabled) {
  39720. return;
  39721. }
  39722. this._bloomEnabled = enabled;
  39723. this._buildPipeline();
  39724. },
  39725. enumerable: true,
  39726. configurable: true
  39727. });
  39728. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  39729. get: function () {
  39730. return this._fxaaEnabled;
  39731. },
  39732. set: function (enabled) {
  39733. if (this._fxaaEnabled === enabled) {
  39734. return;
  39735. }
  39736. this._fxaaEnabled = enabled;
  39737. this._buildPipeline();
  39738. },
  39739. enumerable: true,
  39740. configurable: true
  39741. });
  39742. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  39743. get: function () {
  39744. return this._imageProcessingEnabled;
  39745. },
  39746. set: function (enabled) {
  39747. if (this._imageProcessingEnabled === enabled) {
  39748. return;
  39749. }
  39750. this._imageProcessingEnabled = enabled;
  39751. this._buildPipeline();
  39752. },
  39753. enumerable: true,
  39754. configurable: true
  39755. });
  39756. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  39757. var _this = this;
  39758. var engine = this._scene.getEngine();
  39759. this._disposePostProcesses();
  39760. this._reset();
  39761. if (this.bloomEnabled) {
  39762. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39763. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  39764. if (!this._hdr) {
  39765. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39766. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  39767. this.highlights.autoClear = false;
  39768. this.highlights.alwaysForcePOT = true;
  39769. }
  39770. 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);
  39771. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  39772. this.blurX.alwaysForcePOT = true;
  39773. this.blurX.autoClear = false;
  39774. this.blurX.onActivateObservable.add(function () {
  39775. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  39776. _this.blurX.kernel = _this.bloomKernel * dw;
  39777. });
  39778. 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);
  39779. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  39780. this.blurY.alwaysForcePOT = true;
  39781. this.blurY.autoClear = false;
  39782. this.blurY.onActivateObservable.add(function () {
  39783. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  39784. _this.blurY.kernel = _this.bloomKernel * dh;
  39785. });
  39786. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39787. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  39788. this.copyBack.alwaysForcePOT = true;
  39789. if (this._hdr) {
  39790. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  39791. var w = this.bloomWeight;
  39792. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  39793. }
  39794. else {
  39795. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  39796. }
  39797. this.copyBack.autoClear = false;
  39798. }
  39799. if (this._imageProcessingEnabled) {
  39800. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39801. if (this._hdr) {
  39802. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  39803. }
  39804. }
  39805. if (this.fxaaEnabled) {
  39806. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39807. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  39808. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  39809. }
  39810. else {
  39811. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39812. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  39813. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  39814. }
  39815. if (this.bloomEnabled) {
  39816. if (this._hdr) {
  39817. this.copyBack.shareOutputWith(this.blurX);
  39818. if (this.imageProcessing) {
  39819. this.imageProcessing.shareOutputWith(this.pass);
  39820. this.imageProcessing.autoClear = false;
  39821. }
  39822. else if (this.fxaa) {
  39823. this.fxaa.shareOutputWith(this.pass);
  39824. }
  39825. else {
  39826. this.finalMerge.shareOutputWith(this.pass);
  39827. }
  39828. }
  39829. else {
  39830. if (this.fxaa) {
  39831. this.fxaa.shareOutputWith(this.pass);
  39832. }
  39833. else {
  39834. this.finalMerge.shareOutputWith(this.pass);
  39835. }
  39836. }
  39837. }
  39838. if (this._cameras !== null) {
  39839. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  39840. }
  39841. };
  39842. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  39843. for (var i = 0; i < this._cameras.length; i++) {
  39844. var camera = this._cameras[i];
  39845. if (this.pass) {
  39846. this.pass.dispose(camera);
  39847. this.pass = null;
  39848. }
  39849. if (this.highlights) {
  39850. this.highlights.dispose(camera);
  39851. this.highlights = null;
  39852. }
  39853. if (this.blurX) {
  39854. this.blurX.dispose(camera);
  39855. this.blurX = null;
  39856. }
  39857. if (this.blurY) {
  39858. this.blurY.dispose(camera);
  39859. this.blurY = null;
  39860. }
  39861. if (this.copyBack) {
  39862. this.copyBack.dispose(camera);
  39863. this.copyBack = null;
  39864. }
  39865. if (this.imageProcessing) {
  39866. this.imageProcessing.dispose(camera);
  39867. this.imageProcessing = null;
  39868. }
  39869. if (this.fxaa) {
  39870. this.fxaa.dispose(camera);
  39871. this.fxaa = null;
  39872. }
  39873. if (this.finalMerge) {
  39874. this.finalMerge.dispose(camera);
  39875. this.finalMerge = null;
  39876. }
  39877. }
  39878. };
  39879. // Dispose
  39880. DefaultRenderingPipeline.prototype.dispose = function () {
  39881. this._disposePostProcesses();
  39882. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  39883. _super.prototype.dispose.call(this);
  39884. };
  39885. // Serialize rendering pipeline
  39886. DefaultRenderingPipeline.prototype.serialize = function () {
  39887. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39888. serializationObject.customType = "DefaultRenderingPipeline";
  39889. return serializationObject;
  39890. };
  39891. // Parse serialized pipeline
  39892. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  39893. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  39894. };
  39895. return DefaultRenderingPipeline;
  39896. }(BABYLON.PostProcessRenderPipeline));
  39897. __decorate([
  39898. BABYLON.serialize()
  39899. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  39900. __decorate([
  39901. BABYLON.serialize()
  39902. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  39903. __decorate([
  39904. BABYLON.serialize()
  39905. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  39906. __decorate([
  39907. BABYLON.serialize()
  39908. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  39909. __decorate([
  39910. BABYLON.serialize()
  39911. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  39912. __decorate([
  39913. BABYLON.serialize()
  39914. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  39915. __decorate([
  39916. BABYLON.serialize()
  39917. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  39918. __decorate([
  39919. BABYLON.serialize()
  39920. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  39921. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  39922. })(BABYLON || (BABYLON = {}));
  39923. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  39924. /// <reference path="babylon.mesh.ts" />
  39925. var BABYLON;
  39926. (function (BABYLON) {
  39927. var GroundMesh = (function (_super) {
  39928. __extends(GroundMesh, _super);
  39929. function GroundMesh(name, scene) {
  39930. var _this = _super.call(this, name, scene) || this;
  39931. _this.generateOctree = false;
  39932. _this._worldInverse = new BABYLON.Matrix();
  39933. return _this;
  39934. }
  39935. GroundMesh.prototype.getClassName = function () {
  39936. return "GroundMesh";
  39937. };
  39938. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39939. get: function () {
  39940. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39941. },
  39942. enumerable: true,
  39943. configurable: true
  39944. });
  39945. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39946. get: function () {
  39947. return this._subdivisionsX;
  39948. },
  39949. enumerable: true,
  39950. configurable: true
  39951. });
  39952. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39953. get: function () {
  39954. return this._subdivisionsY;
  39955. },
  39956. enumerable: true,
  39957. configurable: true
  39958. });
  39959. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39960. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39961. this._subdivisionsX = chunksCount;
  39962. this._subdivisionsY = chunksCount;
  39963. this.subdivide(chunksCount);
  39964. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39965. };
  39966. /**
  39967. * Returns a height (y) value in the Worl system :
  39968. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39969. * Returns the ground y position if (x, z) are outside the ground surface.
  39970. */
  39971. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39972. var world = this.getWorldMatrix();
  39973. var invMat = BABYLON.Tmp.Matrix[5];
  39974. world.invertToRef(invMat);
  39975. var tmpVect = BABYLON.Tmp.Vector3[8];
  39976. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39977. x = tmpVect.x;
  39978. z = tmpVect.z;
  39979. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39980. return this.position.y;
  39981. }
  39982. if (!this._heightQuads || this._heightQuads.length == 0) {
  39983. this._initHeightQuads();
  39984. this._computeHeightQuads();
  39985. }
  39986. var facet = this._getFacetAt(x, z);
  39987. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39988. // return y in the World system
  39989. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39990. return tmpVect.y;
  39991. };
  39992. /**
  39993. * Returns a normalized vector (Vector3) orthogonal to the ground
  39994. * at the ground coordinates (x, z) expressed in the World system.
  39995. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39996. */
  39997. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39998. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39999. this.getNormalAtCoordinatesToRef(x, z, normal);
  40000. return normal;
  40001. };
  40002. /**
  40003. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40004. * at the ground coordinates (x, z) expressed in the World system.
  40005. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40006. * Returns the GroundMesh.
  40007. */
  40008. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40009. var world = this.getWorldMatrix();
  40010. var tmpMat = BABYLON.Tmp.Matrix[5];
  40011. world.invertToRef(tmpMat);
  40012. var tmpVect = BABYLON.Tmp.Vector3[8];
  40013. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40014. x = tmpVect.x;
  40015. z = tmpVect.z;
  40016. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40017. return this;
  40018. }
  40019. if (!this._heightQuads || this._heightQuads.length == 0) {
  40020. this._initHeightQuads();
  40021. this._computeHeightQuads();
  40022. }
  40023. var facet = this._getFacetAt(x, z);
  40024. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40025. return this;
  40026. };
  40027. /**
  40028. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40029. * if the ground has been updated.
  40030. * This can be used in the render loop.
  40031. * Returns the GroundMesh.
  40032. */
  40033. GroundMesh.prototype.updateCoordinateHeights = function () {
  40034. if (!this._heightQuads || this._heightQuads.length == 0) {
  40035. this._initHeightQuads();
  40036. }
  40037. this._computeHeightQuads();
  40038. return this;
  40039. };
  40040. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40041. GroundMesh.prototype._getFacetAt = function (x, z) {
  40042. // retrieve col and row from x, z coordinates in the ground local system
  40043. var subdivisionsX = this._subdivisionsX;
  40044. var subdivisionsY = this._subdivisionsY;
  40045. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40046. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40047. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40048. var facet;
  40049. if (z < quad.slope.x * x + quad.slope.y) {
  40050. facet = quad.facet1;
  40051. }
  40052. else {
  40053. facet = quad.facet2;
  40054. }
  40055. return facet;
  40056. };
  40057. // Creates and populates the heightMap array with "facet" elements :
  40058. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40059. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40060. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40061. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40062. // Returns the GroundMesh.
  40063. GroundMesh.prototype._initHeightQuads = function () {
  40064. var subdivisionsX = this._subdivisionsX;
  40065. var subdivisionsY = this._subdivisionsY;
  40066. this._heightQuads = new Array();
  40067. for (var row = 0; row < subdivisionsY; row++) {
  40068. for (var col = 0; col < subdivisionsX; col++) {
  40069. 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) };
  40070. this._heightQuads[row * subdivisionsX + col] = quad;
  40071. }
  40072. }
  40073. return this;
  40074. };
  40075. // Compute each quad element values and update the the heightMap array :
  40076. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40077. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40078. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40079. // Returns the GroundMesh.
  40080. GroundMesh.prototype._computeHeightQuads = function () {
  40081. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40082. var v1 = BABYLON.Tmp.Vector3[3];
  40083. var v2 = BABYLON.Tmp.Vector3[2];
  40084. var v3 = BABYLON.Tmp.Vector3[1];
  40085. var v4 = BABYLON.Tmp.Vector3[0];
  40086. var v1v2 = BABYLON.Tmp.Vector3[4];
  40087. var v1v3 = BABYLON.Tmp.Vector3[5];
  40088. var v1v4 = BABYLON.Tmp.Vector3[6];
  40089. var norm1 = BABYLON.Tmp.Vector3[7];
  40090. var norm2 = BABYLON.Tmp.Vector3[8];
  40091. var i = 0;
  40092. var j = 0;
  40093. var k = 0;
  40094. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40095. var h = 0;
  40096. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40097. var d2 = 0;
  40098. var subdivisionsX = this._subdivisionsX;
  40099. var subdivisionsY = this._subdivisionsY;
  40100. for (var row = 0; row < subdivisionsY; row++) {
  40101. for (var col = 0; col < subdivisionsX; col++) {
  40102. i = col * 3;
  40103. j = row * (subdivisionsX + 1) * 3;
  40104. k = (row + 1) * (subdivisionsX + 1) * 3;
  40105. v1.x = positions[j + i];
  40106. v1.y = positions[j + i + 1];
  40107. v1.z = positions[j + i + 2];
  40108. v2.x = positions[j + i + 3];
  40109. v2.y = positions[j + i + 4];
  40110. v2.z = positions[j + i + 5];
  40111. v3.x = positions[k + i];
  40112. v3.y = positions[k + i + 1];
  40113. v3.z = positions[k + i + 2];
  40114. v4.x = positions[k + i + 3];
  40115. v4.y = positions[k + i + 4];
  40116. v4.z = positions[k + i + 5];
  40117. // 2D slope V1V4
  40118. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40119. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40120. // facet equations :
  40121. // we compute each facet normal vector
  40122. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40123. // we compute the value d by applying the equation to v1 which belongs to the plane
  40124. // then we store the facet equation in a Vector4
  40125. v2.subtractToRef(v1, v1v2);
  40126. v3.subtractToRef(v1, v1v3);
  40127. v4.subtractToRef(v1, v1v4);
  40128. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40129. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40130. norm1.normalize();
  40131. norm2.normalize();
  40132. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40133. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40134. var quad = this._heightQuads[row * subdivisionsX + col];
  40135. quad.slope.copyFromFloats(cd, h);
  40136. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  40137. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  40138. }
  40139. }
  40140. return this;
  40141. };
  40142. GroundMesh.prototype.serialize = function (serializationObject) {
  40143. _super.prototype.serialize.call(this, serializationObject);
  40144. serializationObject.subdivisionsX = this._subdivisionsX;
  40145. serializationObject.subdivisionsY = this._subdivisionsY;
  40146. serializationObject.minX = this._minX;
  40147. serializationObject.maxX = this._maxX;
  40148. serializationObject.minZ = this._minZ;
  40149. serializationObject.maxZ = this._maxZ;
  40150. serializationObject.width = this._width;
  40151. serializationObject.height = this._height;
  40152. };
  40153. GroundMesh.Parse = function (parsedMesh, scene) {
  40154. var result = new GroundMesh(parsedMesh.name, scene);
  40155. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  40156. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  40157. result._minX = parsedMesh.minX;
  40158. result._maxX = parsedMesh.maxX;
  40159. result._minZ = parsedMesh.minZ;
  40160. result._maxZ = parsedMesh.maxZ;
  40161. result._width = parsedMesh.width;
  40162. result._height = parsedMesh.height;
  40163. return result;
  40164. };
  40165. return GroundMesh;
  40166. }(BABYLON.Mesh));
  40167. BABYLON.GroundMesh = GroundMesh;
  40168. })(BABYLON || (BABYLON = {}));
  40169. //# sourceMappingURL=babylon.groundMesh.js.map
  40170. var BABYLON;
  40171. (function (BABYLON) {
  40172. /**
  40173. * Creates an instance based on a source mesh.
  40174. */
  40175. var InstancedMesh = (function (_super) {
  40176. __extends(InstancedMesh, _super);
  40177. function InstancedMesh(name, source) {
  40178. var _this = _super.call(this, name, source.getScene()) || this;
  40179. source.instances.push(_this);
  40180. _this._sourceMesh = source;
  40181. _this.position.copyFrom(source.position);
  40182. _this.rotation.copyFrom(source.rotation);
  40183. _this.scaling.copyFrom(source.scaling);
  40184. if (source.rotationQuaternion) {
  40185. _this.rotationQuaternion = source.rotationQuaternion.clone();
  40186. }
  40187. _this.infiniteDistance = source.infiniteDistance;
  40188. _this.setPivotMatrix(source.getPivotMatrix());
  40189. _this.refreshBoundingInfo();
  40190. _this._syncSubMeshes();
  40191. return _this;
  40192. }
  40193. /**
  40194. * Returns the string "InstancedMesh".
  40195. */
  40196. InstancedMesh.prototype.getClassName = function () {
  40197. return "InstancedMesh";
  40198. };
  40199. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  40200. // Methods
  40201. get: function () {
  40202. return this._sourceMesh.receiveShadows;
  40203. },
  40204. enumerable: true,
  40205. configurable: true
  40206. });
  40207. Object.defineProperty(InstancedMesh.prototype, "material", {
  40208. get: function () {
  40209. return this._sourceMesh.material;
  40210. },
  40211. enumerable: true,
  40212. configurable: true
  40213. });
  40214. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  40215. get: function () {
  40216. return this._sourceMesh.visibility;
  40217. },
  40218. enumerable: true,
  40219. configurable: true
  40220. });
  40221. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  40222. get: function () {
  40223. return this._sourceMesh.skeleton;
  40224. },
  40225. enumerable: true,
  40226. configurable: true
  40227. });
  40228. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  40229. get: function () {
  40230. return this._sourceMesh.renderingGroupId;
  40231. },
  40232. enumerable: true,
  40233. configurable: true
  40234. });
  40235. /**
  40236. * Returns the total number of vertices (integer).
  40237. */
  40238. InstancedMesh.prototype.getTotalVertices = function () {
  40239. return this._sourceMesh.getTotalVertices();
  40240. };
  40241. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  40242. get: function () {
  40243. return this._sourceMesh;
  40244. },
  40245. enumerable: true,
  40246. configurable: true
  40247. });
  40248. /**
  40249. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  40250. */
  40251. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  40252. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  40253. };
  40254. /**
  40255. * Sets the vertex data of the mesh geometry for the requested `kind`.
  40256. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  40257. * The `data` are either a numeric array either a Float32Array.
  40258. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  40259. * 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).
  40260. * Note that a new underlying VertexBuffer object is created each call.
  40261. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  40262. *
  40263. * Possible `kind` values :
  40264. * - BABYLON.VertexBuffer.PositionKind
  40265. * - BABYLON.VertexBuffer.UVKind
  40266. * - BABYLON.VertexBuffer.UV2Kind
  40267. * - BABYLON.VertexBuffer.UV3Kind
  40268. * - BABYLON.VertexBuffer.UV4Kind
  40269. * - BABYLON.VertexBuffer.UV5Kind
  40270. * - BABYLON.VertexBuffer.UV6Kind
  40271. * - BABYLON.VertexBuffer.ColorKind
  40272. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40273. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40274. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40275. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40276. *
  40277. * Returns the Mesh.
  40278. */
  40279. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40280. if (this.sourceMesh) {
  40281. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  40282. }
  40283. return this.sourceMesh;
  40284. };
  40285. /**
  40286. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  40287. * If the mesh has no geometry, it is simply returned as it is.
  40288. * The `data` are either a numeric array either a Float32Array.
  40289. * No new underlying VertexBuffer object is created.
  40290. * 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.
  40291. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  40292. *
  40293. * Possible `kind` values :
  40294. * - BABYLON.VertexBuffer.PositionKind
  40295. * - BABYLON.VertexBuffer.UVKind
  40296. * - BABYLON.VertexBuffer.UV2Kind
  40297. * - BABYLON.VertexBuffer.UV3Kind
  40298. * - BABYLON.VertexBuffer.UV4Kind
  40299. * - BABYLON.VertexBuffer.UV5Kind
  40300. * - BABYLON.VertexBuffer.UV6Kind
  40301. * - BABYLON.VertexBuffer.ColorKind
  40302. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40303. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40304. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40305. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40306. *
  40307. * Returns the Mesh.
  40308. */
  40309. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  40310. if (this.sourceMesh) {
  40311. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  40312. }
  40313. return this.sourceMesh;
  40314. };
  40315. /**
  40316. * Sets the mesh indices.
  40317. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  40318. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  40319. * This method creates a new index buffer each call.
  40320. * Returns the Mesh.
  40321. */
  40322. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  40323. if (this.sourceMesh) {
  40324. this.sourceMesh.setIndices(indices, totalVertices);
  40325. }
  40326. return this.sourceMesh;
  40327. };
  40328. /**
  40329. * Boolean : True if the mesh owns the requested kind of data.
  40330. */
  40331. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  40332. return this._sourceMesh.isVerticesDataPresent(kind);
  40333. };
  40334. /**
  40335. * Returns an array of indices (IndicesArray).
  40336. */
  40337. InstancedMesh.prototype.getIndices = function () {
  40338. return this._sourceMesh.getIndices();
  40339. };
  40340. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  40341. get: function () {
  40342. return this._sourceMesh._positions;
  40343. },
  40344. enumerable: true,
  40345. configurable: true
  40346. });
  40347. /**
  40348. * Sets a new updated BoundingInfo to the mesh.
  40349. * Returns the mesh.
  40350. */
  40351. InstancedMesh.prototype.refreshBoundingInfo = function () {
  40352. var meshBB = this._sourceMesh.getBoundingInfo();
  40353. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  40354. this._updateBoundingInfo();
  40355. return this;
  40356. };
  40357. InstancedMesh.prototype._preActivate = function () {
  40358. if (this._currentLOD) {
  40359. this._currentLOD._preActivate();
  40360. }
  40361. return this;
  40362. };
  40363. InstancedMesh.prototype._activate = function (renderId) {
  40364. if (this._currentLOD) {
  40365. this._currentLOD._registerInstanceForRenderId(this, renderId);
  40366. }
  40367. return this;
  40368. };
  40369. /**
  40370. * Returns the current associated LOD AbstractMesh.
  40371. */
  40372. InstancedMesh.prototype.getLOD = function (camera) {
  40373. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  40374. if (this._currentLOD === this.sourceMesh) {
  40375. return this;
  40376. }
  40377. return this._currentLOD;
  40378. };
  40379. InstancedMesh.prototype._syncSubMeshes = function () {
  40380. this.releaseSubMeshes();
  40381. if (this._sourceMesh.subMeshes) {
  40382. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  40383. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  40384. }
  40385. }
  40386. return this;
  40387. };
  40388. InstancedMesh.prototype._generatePointsArray = function () {
  40389. return this._sourceMesh._generatePointsArray();
  40390. };
  40391. /**
  40392. * Creates a new InstancedMesh from the current mesh.
  40393. * - name (string) : the cloned mesh name
  40394. * - newParent (optional Node) : the optional Node to parent the clone to.
  40395. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  40396. *
  40397. * Returns the clone.
  40398. */
  40399. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40400. var result = this._sourceMesh.createInstance(name);
  40401. // Deep copy
  40402. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  40403. // Bounding info
  40404. this.refreshBoundingInfo();
  40405. // Parent
  40406. if (newParent) {
  40407. result.parent = newParent;
  40408. }
  40409. if (!doNotCloneChildren) {
  40410. // Children
  40411. for (var index = 0; index < this.getScene().meshes.length; index++) {
  40412. var mesh = this.getScene().meshes[index];
  40413. if (mesh.parent === this) {
  40414. mesh.clone(mesh.name, result);
  40415. }
  40416. }
  40417. }
  40418. result.computeWorldMatrix(true);
  40419. return result;
  40420. };
  40421. /**
  40422. * Disposes the InstancedMesh.
  40423. * Returns nothing.
  40424. */
  40425. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  40426. // Remove from mesh
  40427. var index = this._sourceMesh.instances.indexOf(this);
  40428. this._sourceMesh.instances.splice(index, 1);
  40429. _super.prototype.dispose.call(this, doNotRecurse);
  40430. };
  40431. return InstancedMesh;
  40432. }(BABYLON.AbstractMesh));
  40433. BABYLON.InstancedMesh = InstancedMesh;
  40434. })(BABYLON || (BABYLON = {}));
  40435. //# sourceMappingURL=babylon.instancedMesh.js.map
  40436. /// <reference path="babylon.mesh.ts" />
  40437. var BABYLON;
  40438. (function (BABYLON) {
  40439. var LinesMesh = (function (_super) {
  40440. __extends(LinesMesh, _super);
  40441. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  40442. if (parent === void 0) { parent = null; }
  40443. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40444. _this.useVertexColor = useVertexColor;
  40445. _this.color = new BABYLON.Color3(1, 1, 1);
  40446. _this.alpha = 1;
  40447. if (source) {
  40448. _this.color = source.color.clone();
  40449. _this.alpha = source.alpha;
  40450. _this.useVertexColor = source.useVertexColor;
  40451. }
  40452. _this._intersectionThreshold = 0.1;
  40453. var options = {
  40454. attributes: [BABYLON.VertexBuffer.PositionKind],
  40455. uniforms: ["world", "viewProjection"],
  40456. needAlphaBlending: false,
  40457. };
  40458. if (!useVertexColor) {
  40459. options.uniforms.push("color");
  40460. options.needAlphaBlending = true;
  40461. }
  40462. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  40463. return _this;
  40464. }
  40465. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40466. /**
  40467. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40468. * This margin is expressed in world space coordinates, so its value may vary.
  40469. * Default value is 0.1
  40470. * @returns the intersection Threshold value.
  40471. */
  40472. get: function () {
  40473. return this._intersectionThreshold;
  40474. },
  40475. /**
  40476. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40477. * This margin is expressed in world space coordinates, so its value may vary.
  40478. * @param value the new threshold to apply
  40479. */
  40480. set: function (value) {
  40481. if (this._intersectionThreshold === value) {
  40482. return;
  40483. }
  40484. this._intersectionThreshold = value;
  40485. if (this.geometry) {
  40486. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40487. }
  40488. },
  40489. enumerable: true,
  40490. configurable: true
  40491. });
  40492. /**
  40493. * Returns the string "LineMesh"
  40494. */
  40495. LinesMesh.prototype.getClassName = function () {
  40496. return "LinesMesh";
  40497. };
  40498. Object.defineProperty(LinesMesh.prototype, "material", {
  40499. get: function () {
  40500. return this._colorShader;
  40501. },
  40502. enumerable: true,
  40503. configurable: true
  40504. });
  40505. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40506. get: function () {
  40507. return false;
  40508. },
  40509. enumerable: true,
  40510. configurable: true
  40511. });
  40512. LinesMesh.prototype.createInstance = function (name) {
  40513. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40514. return null;
  40515. };
  40516. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40517. // VBOs
  40518. this._geometry._bind(this._colorShader.getEffect());
  40519. // Color
  40520. if (!this.useVertexColor) {
  40521. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40522. }
  40523. return this;
  40524. };
  40525. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40526. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40527. return this;
  40528. }
  40529. var engine = this.getScene().getEngine();
  40530. // Draw order
  40531. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40532. return this;
  40533. };
  40534. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40535. this._colorShader.dispose();
  40536. _super.prototype.dispose.call(this, doNotRecurse);
  40537. };
  40538. /**
  40539. * Returns a new LineMesh object cloned from the current one.
  40540. */
  40541. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40542. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40543. };
  40544. return LinesMesh;
  40545. }(BABYLON.Mesh));
  40546. BABYLON.LinesMesh = LinesMesh;
  40547. })(BABYLON || (BABYLON = {}));
  40548. //# sourceMappingURL=babylon.linesMesh.js.map
  40549. var BABYLON;
  40550. (function (BABYLON) {
  40551. var StandardMaterialDefines = (function (_super) {
  40552. __extends(StandardMaterialDefines, _super);
  40553. function StandardMaterialDefines() {
  40554. var _this = _super.call(this) || this;
  40555. _this.DIFFUSE = false;
  40556. _this.AMBIENT = false;
  40557. _this.OPACITY = false;
  40558. _this.OPACITYRGB = false;
  40559. _this.REFLECTION = false;
  40560. _this.EMISSIVE = false;
  40561. _this.SPECULAR = false;
  40562. _this.BUMP = false;
  40563. _this.PARALLAX = false;
  40564. _this.PARALLAXOCCLUSION = false;
  40565. _this.SPECULAROVERALPHA = false;
  40566. _this.CLIPPLANE = false;
  40567. _this.ALPHATEST = false;
  40568. _this.ALPHAFROMDIFFUSE = false;
  40569. _this.POINTSIZE = false;
  40570. _this.FOG = false;
  40571. _this.SPECULARTERM = false;
  40572. _this.DIFFUSEFRESNEL = false;
  40573. _this.OPACITYFRESNEL = false;
  40574. _this.REFLECTIONFRESNEL = false;
  40575. _this.REFRACTIONFRESNEL = false;
  40576. _this.EMISSIVEFRESNEL = false;
  40577. _this.FRESNEL = false;
  40578. _this.NORMAL = false;
  40579. _this.UV1 = false;
  40580. _this.UV2 = false;
  40581. _this.VERTEXCOLOR = false;
  40582. _this.VERTEXALPHA = false;
  40583. _this.NUM_BONE_INFLUENCERS = 0;
  40584. _this.BonesPerMesh = 0;
  40585. _this.INSTANCES = false;
  40586. _this.GLOSSINESS = false;
  40587. _this.ROUGHNESS = false;
  40588. _this.EMISSIVEASILLUMINATION = false;
  40589. _this.LINKEMISSIVEWITHDIFFUSE = false;
  40590. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  40591. _this.LIGHTMAP = false;
  40592. _this.USELIGHTMAPASSHADOWMAP = false;
  40593. _this.REFLECTIONMAP_3D = false;
  40594. _this.REFLECTIONMAP_SPHERICAL = false;
  40595. _this.REFLECTIONMAP_PLANAR = false;
  40596. _this.REFLECTIONMAP_CUBIC = false;
  40597. _this.REFLECTIONMAP_PROJECTION = false;
  40598. _this.REFLECTIONMAP_SKYBOX = false;
  40599. _this.REFLECTIONMAP_EXPLICIT = false;
  40600. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40601. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40602. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40603. _this.INVERTCUBICMAP = false;
  40604. _this.LOGARITHMICDEPTH = false;
  40605. _this.REFRACTION = false;
  40606. _this.REFRACTIONMAP_3D = false;
  40607. _this.REFLECTIONOVERALPHA = false;
  40608. _this.INVERTNORMALMAPX = false;
  40609. _this.INVERTNORMALMAPY = false;
  40610. _this.TWOSIDEDLIGHTING = false;
  40611. _this.SHADOWFLOAT = false;
  40612. _this.CAMERACOLORGRADING = false;
  40613. _this.CAMERACOLORCURVES = false;
  40614. _this.MORPHTARGETS = false;
  40615. _this.MORPHTARGETS_NORMAL = false;
  40616. _this.MORPHTARGETS_TANGENT = false;
  40617. _this.NUM_MORPH_INFLUENCERS = 0;
  40618. _this.USERIGHTHANDEDSYSTEM = false;
  40619. _this.rebuild();
  40620. return _this;
  40621. }
  40622. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  40623. var modes = [
  40624. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  40625. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  40626. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  40627. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  40628. ];
  40629. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  40630. var mode = modes_1[_i];
  40631. this[mode] = (mode === modeToEnable);
  40632. }
  40633. };
  40634. return StandardMaterialDefines;
  40635. }(BABYLON.MaterialDefines));
  40636. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  40637. var StandardMaterial = (function (_super) {
  40638. __extends(StandardMaterial, _super);
  40639. function StandardMaterial(name, scene) {
  40640. var _this = _super.call(this, name, scene) || this;
  40641. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  40642. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  40643. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  40644. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40645. _this.specularPower = 64;
  40646. _this._useAlphaFromDiffuseTexture = false;
  40647. _this._useEmissiveAsIllumination = false;
  40648. _this._linkEmissiveWithDiffuse = false;
  40649. _this._useSpecularOverAlpha = false;
  40650. _this._useReflectionOverAlpha = false;
  40651. _this._disableLighting = false;
  40652. _this._useParallax = false;
  40653. _this._useParallaxOcclusion = false;
  40654. _this.parallaxScaleBias = 0.05;
  40655. _this._roughness = 0;
  40656. _this.indexOfRefraction = 0.98;
  40657. _this.invertRefractionY = true;
  40658. _this._useLightmapAsShadowmap = false;
  40659. _this._useReflectionFresnelFromSpecular = false;
  40660. _this._useGlossinessFromSpecularMapAlpha = false;
  40661. _this._maxSimultaneousLights = 4;
  40662. /**
  40663. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40664. */
  40665. _this._invertNormalMapX = false;
  40666. /**
  40667. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40668. */
  40669. _this._invertNormalMapY = false;
  40670. /**
  40671. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40672. */
  40673. _this._twoSidedLighting = false;
  40674. /**
  40675. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40676. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40677. * 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;
  40678. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40679. */
  40680. _this._cameraColorCurves = null;
  40681. _this._renderTargets = new BABYLON.SmartArray(16);
  40682. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  40683. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40684. _this.getRenderTargetTextures = function () {
  40685. _this._renderTargets.reset();
  40686. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40687. _this._renderTargets.push(_this._reflectionTexture);
  40688. }
  40689. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40690. _this._renderTargets.push(_this._refractionTexture);
  40691. }
  40692. return _this._renderTargets;
  40693. };
  40694. return _this;
  40695. }
  40696. StandardMaterial.prototype.getClassName = function () {
  40697. return "StandardMaterial";
  40698. };
  40699. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  40700. get: function () {
  40701. return this._useLogarithmicDepth;
  40702. },
  40703. set: function (value) {
  40704. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40705. this._markAllSubMeshesAsMiscDirty();
  40706. },
  40707. enumerable: true,
  40708. configurable: true
  40709. });
  40710. StandardMaterial.prototype.needAlphaBlending = function () {
  40711. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  40712. };
  40713. StandardMaterial.prototype.needAlphaTesting = function () {
  40714. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  40715. };
  40716. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  40717. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  40718. };
  40719. StandardMaterial.prototype.getAlphaTestTexture = function () {
  40720. return this._diffuseTexture;
  40721. };
  40722. /**
  40723. * Child classes can use it to update shaders
  40724. */
  40725. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40726. if (this.isFrozen) {
  40727. if (this._wasPreviouslyReady && subMesh.effect) {
  40728. return true;
  40729. }
  40730. }
  40731. if (!subMesh._materialDefines) {
  40732. subMesh._materialDefines = new StandardMaterialDefines();
  40733. }
  40734. var scene = this.getScene();
  40735. var defines = subMesh._materialDefines;
  40736. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40737. if (defines._renderId === scene.getRenderId()) {
  40738. return true;
  40739. }
  40740. }
  40741. var engine = scene.getEngine();
  40742. // Lights
  40743. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40744. // Textures
  40745. if (defines._areTexturesDirty) {
  40746. defines._needUVs = false;
  40747. if (scene.texturesEnabled) {
  40748. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40749. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  40750. return false;
  40751. }
  40752. else {
  40753. defines._needUVs = true;
  40754. defines.DIFFUSE = true;
  40755. }
  40756. }
  40757. else {
  40758. defines.DIFFUSE = false;
  40759. }
  40760. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40761. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40762. return false;
  40763. }
  40764. else {
  40765. defines._needUVs = true;
  40766. defines.AMBIENT = true;
  40767. }
  40768. }
  40769. else {
  40770. defines.AMBIENT = false;
  40771. }
  40772. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40773. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40774. return false;
  40775. }
  40776. else {
  40777. defines._needUVs = true;
  40778. defines.OPACITY = true;
  40779. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40780. }
  40781. }
  40782. else {
  40783. defines.OPACITY = false;
  40784. }
  40785. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40786. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  40787. return false;
  40788. }
  40789. else {
  40790. defines._needNormals = true;
  40791. defines.REFLECTION = true;
  40792. defines.ROUGHNESS = (this._roughness > 0);
  40793. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  40794. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  40795. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  40796. switch (this._reflectionTexture.coordinatesMode) {
  40797. case BABYLON.Texture.CUBIC_MODE:
  40798. case BABYLON.Texture.INVCUBIC_MODE:
  40799. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  40800. break;
  40801. case BABYLON.Texture.EXPLICIT_MODE:
  40802. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  40803. break;
  40804. case BABYLON.Texture.PLANAR_MODE:
  40805. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  40806. break;
  40807. case BABYLON.Texture.PROJECTION_MODE:
  40808. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  40809. break;
  40810. case BABYLON.Texture.SKYBOX_MODE:
  40811. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  40812. break;
  40813. case BABYLON.Texture.SPHERICAL_MODE:
  40814. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  40815. break;
  40816. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40817. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  40818. break;
  40819. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40820. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  40821. break;
  40822. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40823. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  40824. break;
  40825. }
  40826. }
  40827. }
  40828. else {
  40829. defines.REFLECTION = false;
  40830. }
  40831. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40832. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40833. return false;
  40834. }
  40835. else {
  40836. defines._needUVs = true;
  40837. defines.EMISSIVE = true;
  40838. }
  40839. }
  40840. else {
  40841. defines.EMISSIVE = false;
  40842. }
  40843. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40844. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40845. return false;
  40846. }
  40847. else {
  40848. defines._needUVs = true;
  40849. defines.LIGHTMAP = true;
  40850. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40851. }
  40852. }
  40853. else {
  40854. defines.LIGHTMAP = false;
  40855. }
  40856. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40857. if (!this._specularTexture.isReadyOrNotBlocking()) {
  40858. return false;
  40859. }
  40860. else {
  40861. defines._needUVs = true;
  40862. defines.SPECULAR = true;
  40863. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  40864. }
  40865. }
  40866. else {
  40867. defines.SPECULAR = false;
  40868. }
  40869. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  40870. // Bump texure can not be not blocking.
  40871. if (!this._bumpTexture.isReady()) {
  40872. return false;
  40873. }
  40874. else {
  40875. defines._needUVs = true;
  40876. defines.BUMP = true;
  40877. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  40878. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  40879. defines.PARALLAX = this._useParallax;
  40880. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  40881. }
  40882. }
  40883. else {
  40884. defines.BUMP = false;
  40885. }
  40886. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40887. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40888. return false;
  40889. }
  40890. else {
  40891. defines._needUVs = true;
  40892. defines.REFRACTION = true;
  40893. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40894. }
  40895. }
  40896. else {
  40897. defines.REFRACTION = false;
  40898. }
  40899. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  40900. // Camera Color Grading can not be none blocking.
  40901. if (!this._cameraColorGradingTexture.isReady()) {
  40902. return false;
  40903. }
  40904. else {
  40905. defines.CAMERACOLORGRADING = true;
  40906. }
  40907. }
  40908. else {
  40909. defines.CAMERACOLORGRADING = false;
  40910. }
  40911. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40912. }
  40913. else {
  40914. defines.DIFFUSE = false;
  40915. defines.AMBIENT = false;
  40916. defines.OPACITY = false;
  40917. defines.REFLECTION = false;
  40918. defines.EMISSIVE = false;
  40919. defines.LIGHTMAP = false;
  40920. defines.BUMP = false;
  40921. defines.REFRACTION = false;
  40922. defines.CAMERACOLORGRADING = false;
  40923. }
  40924. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  40925. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40926. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40927. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40928. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40929. }
  40930. if (defines._areFresnelDirty) {
  40931. if (StandardMaterial.FresnelEnabled) {
  40932. // Fresnel
  40933. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40934. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40935. this._reflectionFresnelParameters) {
  40936. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40937. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40938. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40939. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40940. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40941. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40942. defines._needNormals = true;
  40943. defines.FRESNEL = true;
  40944. }
  40945. }
  40946. else {
  40947. defines.FRESNEL = false;
  40948. }
  40949. }
  40950. // Misc.
  40951. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  40952. // Attribs
  40953. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40954. // Values that need to be evaluated on every frame
  40955. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40956. if (scene._mirroredCameraPosition && defines.BUMP) {
  40957. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  40958. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  40959. defines.markAsUnprocessed();
  40960. }
  40961. // Get correct effect
  40962. if (defines.isDirty) {
  40963. defines.markAsProcessed();
  40964. scene.resetCachedMaterial();
  40965. // Fallbacks
  40966. var fallbacks = new BABYLON.EffectFallbacks();
  40967. if (defines.REFLECTION) {
  40968. fallbacks.addFallback(0, "REFLECTION");
  40969. }
  40970. if (defines.SPECULAR) {
  40971. fallbacks.addFallback(0, "SPECULAR");
  40972. }
  40973. if (defines.BUMP) {
  40974. fallbacks.addFallback(0, "BUMP");
  40975. }
  40976. if (defines.PARALLAX) {
  40977. fallbacks.addFallback(1, "PARALLAX");
  40978. }
  40979. if (defines.PARALLAXOCCLUSION) {
  40980. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40981. }
  40982. if (defines.SPECULAROVERALPHA) {
  40983. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40984. }
  40985. if (defines.FOG) {
  40986. fallbacks.addFallback(1, "FOG");
  40987. }
  40988. if (defines.POINTSIZE) {
  40989. fallbacks.addFallback(0, "POINTSIZE");
  40990. }
  40991. if (defines.LOGARITHMICDEPTH) {
  40992. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40993. }
  40994. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40995. if (defines.SPECULARTERM) {
  40996. fallbacks.addFallback(0, "SPECULARTERM");
  40997. }
  40998. if (defines.DIFFUSEFRESNEL) {
  40999. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41000. }
  41001. if (defines.OPACITYFRESNEL) {
  41002. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41003. }
  41004. if (defines.REFLECTIONFRESNEL) {
  41005. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41006. }
  41007. if (defines.EMISSIVEFRESNEL) {
  41008. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41009. }
  41010. if (defines.FRESNEL) {
  41011. fallbacks.addFallback(4, "FRESNEL");
  41012. }
  41013. //Attributes
  41014. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41015. if (defines.NORMAL) {
  41016. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41017. }
  41018. if (defines.UV1) {
  41019. attribs.push(BABYLON.VertexBuffer.UVKind);
  41020. }
  41021. if (defines.UV2) {
  41022. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41023. }
  41024. if (defines.VERTEXCOLOR) {
  41025. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41026. }
  41027. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41028. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41029. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41030. var shaderName = "default";
  41031. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41032. "vFogInfos", "vFogColor", "pointSize",
  41033. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41034. "mBones",
  41035. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41036. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41037. "logarithmicDepthConstant"
  41038. ];
  41039. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41040. var uniformBuffers = ["Material", "Scene"];
  41041. if (defines.CAMERACOLORCURVES) {
  41042. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41043. }
  41044. if (defines.CAMERACOLORGRADING) {
  41045. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  41046. }
  41047. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41048. uniformsNames: uniforms,
  41049. uniformBuffersNames: uniformBuffers,
  41050. samplers: samplers,
  41051. defines: defines,
  41052. maxSimultaneousLights: this._maxSimultaneousLights
  41053. });
  41054. if (this.customShaderNameResolve) {
  41055. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41056. }
  41057. var join = defines.toString();
  41058. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41059. attributes: attribs,
  41060. uniformsNames: uniforms,
  41061. uniformBuffersNames: uniformBuffers,
  41062. samplers: samplers,
  41063. defines: join,
  41064. fallbacks: fallbacks,
  41065. onCompiled: this.onCompiled,
  41066. onError: this.onError,
  41067. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41068. }, engine), defines);
  41069. this.buildUniformLayout();
  41070. }
  41071. if (!subMesh.effect.isReady()) {
  41072. return false;
  41073. }
  41074. defines._renderId = scene.getRenderId();
  41075. this._wasPreviouslyReady = true;
  41076. return true;
  41077. };
  41078. StandardMaterial.prototype.buildUniformLayout = function () {
  41079. // Order is important !
  41080. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41081. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41082. this._uniformBuffer.addUniform("opacityParts", 4);
  41083. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41084. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41085. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41086. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41087. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41088. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41089. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41090. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41091. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41092. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41093. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41094. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41095. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41096. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41097. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41098. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41099. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41100. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41101. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41102. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41103. this._uniformBuffer.addUniform("specularMatrix", 16);
  41104. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41105. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41106. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41107. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41108. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41109. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41110. this._uniformBuffer.addUniform("pointSize", 1);
  41111. this._uniformBuffer.create();
  41112. };
  41113. StandardMaterial.prototype.unbind = function () {
  41114. if (this._activeEffect) {
  41115. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41116. this._activeEffect.setTexture("reflection2DSampler", null);
  41117. }
  41118. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41119. this._activeEffect.setTexture("refraction2DSampler", null);
  41120. }
  41121. }
  41122. _super.prototype.unbind.call(this);
  41123. };
  41124. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41125. var scene = this.getScene();
  41126. var defines = subMesh._materialDefines;
  41127. if (!defines) {
  41128. return;
  41129. }
  41130. var effect = subMesh.effect;
  41131. this._activeEffect = effect;
  41132. // Matrices
  41133. this.bindOnlyWorldMatrix(world);
  41134. // Bones
  41135. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41136. if (this._mustRebind(scene, effect, mesh.visibility)) {
  41137. this._uniformBuffer.bindToEffect(effect, "Material");
  41138. this.bindViewProjection(effect);
  41139. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41140. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41141. // Fresnel
  41142. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  41143. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  41144. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  41145. }
  41146. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  41147. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  41148. }
  41149. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  41150. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  41151. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  41152. }
  41153. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  41154. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  41155. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  41156. }
  41157. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  41158. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  41159. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41160. }
  41161. }
  41162. // Textures
  41163. if (scene.texturesEnabled) {
  41164. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41165. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41166. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  41167. }
  41168. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41169. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41170. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  41171. }
  41172. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41173. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41174. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  41175. }
  41176. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41177. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41178. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41179. }
  41180. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41181. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41182. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  41183. }
  41184. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41185. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41186. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  41187. }
  41188. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41189. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  41190. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  41191. }
  41192. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41193. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  41194. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  41195. }
  41196. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41197. var depth = 1.0;
  41198. if (!this._refractionTexture.isCube) {
  41199. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  41200. if (this._refractionTexture.depth) {
  41201. depth = this._refractionTexture.depth;
  41202. }
  41203. }
  41204. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  41205. }
  41206. }
  41207. // Point size
  41208. if (this.pointsCloud) {
  41209. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41210. }
  41211. if (defines.SPECULARTERM) {
  41212. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  41213. }
  41214. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  41215. // Diffuse
  41216. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  41217. }
  41218. // Textures
  41219. if (scene.texturesEnabled) {
  41220. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41221. effect.setTexture("diffuseSampler", this._diffuseTexture);
  41222. }
  41223. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41224. effect.setTexture("ambientSampler", this._ambientTexture);
  41225. }
  41226. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41227. effect.setTexture("opacitySampler", this._opacityTexture);
  41228. }
  41229. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41230. if (this._reflectionTexture.isCube) {
  41231. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  41232. }
  41233. else {
  41234. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  41235. }
  41236. }
  41237. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41238. effect.setTexture("emissiveSampler", this._emissiveTexture);
  41239. }
  41240. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41241. effect.setTexture("lightmapSampler", this._lightmapTexture);
  41242. }
  41243. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41244. effect.setTexture("specularSampler", this._specularTexture);
  41245. }
  41246. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41247. effect.setTexture("bumpSampler", this._bumpTexture);
  41248. }
  41249. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41250. var depth = 1.0;
  41251. if (this._refractionTexture.isCube) {
  41252. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  41253. }
  41254. else {
  41255. effect.setTexture("refraction2DSampler", this._refractionTexture);
  41256. }
  41257. }
  41258. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  41259. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  41260. }
  41261. }
  41262. // Clip plane
  41263. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  41264. // Colors
  41265. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  41266. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  41267. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41268. }
  41269. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  41270. // Lights
  41271. if (scene.lightsEnabled && !this._disableLighting) {
  41272. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  41273. }
  41274. // View
  41275. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  41276. this.bindView(effect);
  41277. }
  41278. // Fog
  41279. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  41280. // Morph targets
  41281. if (defines.NUM_MORPH_INFLUENCERS) {
  41282. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  41283. }
  41284. // Log. depth
  41285. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  41286. // Color Curves
  41287. if (this._cameraColorCurves) {
  41288. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  41289. }
  41290. }
  41291. this._uniformBuffer.update();
  41292. this._afterBind(mesh, this._activeEffect);
  41293. };
  41294. StandardMaterial.prototype.getAnimatables = function () {
  41295. var results = [];
  41296. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  41297. results.push(this._diffuseTexture);
  41298. }
  41299. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41300. results.push(this._ambientTexture);
  41301. }
  41302. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41303. results.push(this._opacityTexture);
  41304. }
  41305. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41306. results.push(this._reflectionTexture);
  41307. }
  41308. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41309. results.push(this._emissiveTexture);
  41310. }
  41311. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  41312. results.push(this._specularTexture);
  41313. }
  41314. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41315. results.push(this._bumpTexture);
  41316. }
  41317. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41318. results.push(this._lightmapTexture);
  41319. }
  41320. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41321. results.push(this._refractionTexture);
  41322. }
  41323. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  41324. results.push(this._cameraColorGradingTexture);
  41325. }
  41326. return results;
  41327. };
  41328. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41329. if (forceDisposeTextures) {
  41330. if (this._diffuseTexture) {
  41331. this._diffuseTexture.dispose();
  41332. }
  41333. if (this._ambientTexture) {
  41334. this._ambientTexture.dispose();
  41335. }
  41336. if (this._opacityTexture) {
  41337. this._opacityTexture.dispose();
  41338. }
  41339. if (this._reflectionTexture) {
  41340. this._reflectionTexture.dispose();
  41341. }
  41342. if (this._emissiveTexture) {
  41343. this._emissiveTexture.dispose();
  41344. }
  41345. if (this._specularTexture) {
  41346. this._specularTexture.dispose();
  41347. }
  41348. if (this._bumpTexture) {
  41349. this._bumpTexture.dispose();
  41350. }
  41351. if (this._lightmapTexture) {
  41352. this._lightmapTexture.dispose();
  41353. }
  41354. if (this._refractionTexture) {
  41355. this._refractionTexture.dispose();
  41356. }
  41357. if (this._cameraColorGradingTexture) {
  41358. this._cameraColorGradingTexture.dispose();
  41359. }
  41360. }
  41361. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41362. };
  41363. StandardMaterial.prototype.clone = function (name) {
  41364. var _this = this;
  41365. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  41366. result.name = name;
  41367. result.id = name;
  41368. return result;
  41369. };
  41370. StandardMaterial.prototype.serialize = function () {
  41371. return BABYLON.SerializationHelper.Serialize(this);
  41372. };
  41373. // Statics
  41374. StandardMaterial.Parse = function (source, scene, rootUrl) {
  41375. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  41376. };
  41377. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  41378. get: function () {
  41379. return StandardMaterial._DiffuseTextureEnabled;
  41380. },
  41381. set: function (value) {
  41382. if (StandardMaterial._DiffuseTextureEnabled === value) {
  41383. return;
  41384. }
  41385. StandardMaterial._DiffuseTextureEnabled = value;
  41386. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41387. },
  41388. enumerable: true,
  41389. configurable: true
  41390. });
  41391. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  41392. get: function () {
  41393. return StandardMaterial._AmbientTextureEnabled;
  41394. },
  41395. set: function (value) {
  41396. if (StandardMaterial._AmbientTextureEnabled === value) {
  41397. return;
  41398. }
  41399. StandardMaterial._AmbientTextureEnabled = value;
  41400. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41401. },
  41402. enumerable: true,
  41403. configurable: true
  41404. });
  41405. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  41406. get: function () {
  41407. return StandardMaterial._OpacityTextureEnabled;
  41408. },
  41409. set: function (value) {
  41410. if (StandardMaterial._OpacityTextureEnabled === value) {
  41411. return;
  41412. }
  41413. StandardMaterial._OpacityTextureEnabled = value;
  41414. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41415. },
  41416. enumerable: true,
  41417. configurable: true
  41418. });
  41419. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  41420. get: function () {
  41421. return StandardMaterial._ReflectionTextureEnabled;
  41422. },
  41423. set: function (value) {
  41424. if (StandardMaterial._ReflectionTextureEnabled === value) {
  41425. return;
  41426. }
  41427. StandardMaterial._ReflectionTextureEnabled = value;
  41428. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41429. },
  41430. enumerable: true,
  41431. configurable: true
  41432. });
  41433. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  41434. get: function () {
  41435. return StandardMaterial._EmissiveTextureEnabled;
  41436. },
  41437. set: function (value) {
  41438. if (StandardMaterial._EmissiveTextureEnabled === value) {
  41439. return;
  41440. }
  41441. StandardMaterial._EmissiveTextureEnabled = value;
  41442. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41443. },
  41444. enumerable: true,
  41445. configurable: true
  41446. });
  41447. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  41448. get: function () {
  41449. return StandardMaterial._SpecularTextureEnabled;
  41450. },
  41451. set: function (value) {
  41452. if (StandardMaterial._SpecularTextureEnabled === value) {
  41453. return;
  41454. }
  41455. StandardMaterial._SpecularTextureEnabled = value;
  41456. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41457. },
  41458. enumerable: true,
  41459. configurable: true
  41460. });
  41461. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  41462. get: function () {
  41463. return StandardMaterial._BumpTextureEnabled;
  41464. },
  41465. set: function (value) {
  41466. if (StandardMaterial._BumpTextureEnabled === value) {
  41467. return;
  41468. }
  41469. StandardMaterial._BumpTextureEnabled = value;
  41470. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41471. },
  41472. enumerable: true,
  41473. configurable: true
  41474. });
  41475. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  41476. get: function () {
  41477. return StandardMaterial._LightmapTextureEnabled;
  41478. },
  41479. set: function (value) {
  41480. if (StandardMaterial._LightmapTextureEnabled === value) {
  41481. return;
  41482. }
  41483. StandardMaterial._LightmapTextureEnabled = value;
  41484. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  41490. get: function () {
  41491. return StandardMaterial._RefractionTextureEnabled;
  41492. },
  41493. set: function (value) {
  41494. if (StandardMaterial._RefractionTextureEnabled === value) {
  41495. return;
  41496. }
  41497. StandardMaterial._RefractionTextureEnabled = value;
  41498. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  41504. get: function () {
  41505. return StandardMaterial._ColorGradingTextureEnabled;
  41506. },
  41507. set: function (value) {
  41508. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  41509. return;
  41510. }
  41511. StandardMaterial._ColorGradingTextureEnabled = value;
  41512. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41513. },
  41514. enumerable: true,
  41515. configurable: true
  41516. });
  41517. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  41518. get: function () {
  41519. return StandardMaterial._FresnelEnabled;
  41520. },
  41521. set: function (value) {
  41522. if (StandardMaterial._FresnelEnabled === value) {
  41523. return;
  41524. }
  41525. StandardMaterial._FresnelEnabled = value;
  41526. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  41527. },
  41528. enumerable: true,
  41529. configurable: true
  41530. });
  41531. return StandardMaterial;
  41532. }(BABYLON.PushMaterial));
  41533. // Flags used to enable or disable a type of texture for all Standard Materials
  41534. StandardMaterial._DiffuseTextureEnabled = true;
  41535. StandardMaterial._AmbientTextureEnabled = true;
  41536. StandardMaterial._OpacityTextureEnabled = true;
  41537. StandardMaterial._ReflectionTextureEnabled = true;
  41538. StandardMaterial._EmissiveTextureEnabled = true;
  41539. StandardMaterial._SpecularTextureEnabled = true;
  41540. StandardMaterial._BumpTextureEnabled = true;
  41541. StandardMaterial._LightmapTextureEnabled = true;
  41542. StandardMaterial._RefractionTextureEnabled = true;
  41543. StandardMaterial._ColorGradingTextureEnabled = true;
  41544. StandardMaterial._FresnelEnabled = true;
  41545. __decorate([
  41546. BABYLON.serializeAsTexture("diffuseTexture")
  41547. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  41548. __decorate([
  41549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41550. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  41551. __decorate([
  41552. BABYLON.serializeAsTexture("ambientTexture")
  41553. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  41554. __decorate([
  41555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41556. ], StandardMaterial.prototype, "ambientTexture", void 0);
  41557. __decorate([
  41558. BABYLON.serializeAsTexture("opacityTexture")
  41559. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  41560. __decorate([
  41561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41562. ], StandardMaterial.prototype, "opacityTexture", void 0);
  41563. __decorate([
  41564. BABYLON.serializeAsTexture("reflectionTexture")
  41565. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  41566. __decorate([
  41567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41568. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  41569. __decorate([
  41570. BABYLON.serializeAsTexture("emissiveTexture")
  41571. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  41572. __decorate([
  41573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41574. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  41575. __decorate([
  41576. BABYLON.serializeAsTexture("specularTexture")
  41577. ], StandardMaterial.prototype, "_specularTexture", void 0);
  41578. __decorate([
  41579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41580. ], StandardMaterial.prototype, "specularTexture", void 0);
  41581. __decorate([
  41582. BABYLON.serializeAsTexture("bumpTexture")
  41583. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  41584. __decorate([
  41585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41586. ], StandardMaterial.prototype, "bumpTexture", void 0);
  41587. __decorate([
  41588. BABYLON.serializeAsTexture("lightmapTexture")
  41589. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  41590. __decorate([
  41591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41592. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  41593. __decorate([
  41594. BABYLON.serializeAsTexture("refractionTexture")
  41595. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  41596. __decorate([
  41597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41598. ], StandardMaterial.prototype, "refractionTexture", void 0);
  41599. __decorate([
  41600. BABYLON.serializeAsColor3("ambient")
  41601. ], StandardMaterial.prototype, "ambientColor", void 0);
  41602. __decorate([
  41603. BABYLON.serializeAsColor3("diffuse")
  41604. ], StandardMaterial.prototype, "diffuseColor", void 0);
  41605. __decorate([
  41606. BABYLON.serializeAsColor3("specular")
  41607. ], StandardMaterial.prototype, "specularColor", void 0);
  41608. __decorate([
  41609. BABYLON.serializeAsColor3("emissive")
  41610. ], StandardMaterial.prototype, "emissiveColor", void 0);
  41611. __decorate([
  41612. BABYLON.serialize()
  41613. ], StandardMaterial.prototype, "specularPower", void 0);
  41614. __decorate([
  41615. BABYLON.serialize("useAlphaFromDiffuseTexture")
  41616. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  41617. __decorate([
  41618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41619. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  41620. __decorate([
  41621. BABYLON.serialize("useEmissiveAsIllumination")
  41622. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  41623. __decorate([
  41624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41625. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  41626. __decorate([
  41627. BABYLON.serialize("linkEmissiveWithDiffuse")
  41628. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  41629. __decorate([
  41630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41631. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  41632. __decorate([
  41633. BABYLON.serialize("useSpecularOverAlpha")
  41634. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  41635. __decorate([
  41636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41637. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  41638. __decorate([
  41639. BABYLON.serialize("useReflectionOverAlpha")
  41640. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  41641. __decorate([
  41642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41643. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  41644. __decorate([
  41645. BABYLON.serialize("disableLighting")
  41646. ], StandardMaterial.prototype, "_disableLighting", void 0);
  41647. __decorate([
  41648. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41649. ], StandardMaterial.prototype, "disableLighting", void 0);
  41650. __decorate([
  41651. BABYLON.serialize("useParallax")
  41652. ], StandardMaterial.prototype, "_useParallax", void 0);
  41653. __decorate([
  41654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41655. ], StandardMaterial.prototype, "useParallax", void 0);
  41656. __decorate([
  41657. BABYLON.serialize("useParallaxOcclusion")
  41658. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  41659. __decorate([
  41660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41661. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  41662. __decorate([
  41663. BABYLON.serialize()
  41664. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  41665. __decorate([
  41666. BABYLON.serialize("roughness")
  41667. ], StandardMaterial.prototype, "_roughness", void 0);
  41668. __decorate([
  41669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41670. ], StandardMaterial.prototype, "roughness", void 0);
  41671. __decorate([
  41672. BABYLON.serialize()
  41673. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  41674. __decorate([
  41675. BABYLON.serialize()
  41676. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  41677. __decorate([
  41678. BABYLON.serialize("useLightmapAsShadowmap")
  41679. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  41680. __decorate([
  41681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41682. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41683. __decorate([
  41684. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  41685. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  41686. __decorate([
  41687. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41688. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  41689. __decorate([
  41690. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  41691. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  41692. __decorate([
  41693. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41694. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  41695. __decorate([
  41696. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  41697. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  41698. __decorate([
  41699. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41700. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  41701. __decorate([
  41702. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  41703. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  41704. __decorate([
  41705. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41706. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  41707. __decorate([
  41708. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  41709. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  41710. __decorate([
  41711. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41712. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  41713. __decorate([
  41714. BABYLON.serialize("useReflectionFresnelFromSpecular")
  41715. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  41716. __decorate([
  41717. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41718. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  41719. __decorate([
  41720. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  41721. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  41722. __decorate([
  41723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41724. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  41725. __decorate([
  41726. BABYLON.serialize("maxSimultaneousLights")
  41727. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  41728. __decorate([
  41729. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41730. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  41731. __decorate([
  41732. BABYLON.serialize("invertNormalMapX")
  41733. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  41734. __decorate([
  41735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41736. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  41737. __decorate([
  41738. BABYLON.serialize("invertNormalMapY")
  41739. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  41740. __decorate([
  41741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41742. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  41743. __decorate([
  41744. BABYLON.serialize("twoSidedLighting")
  41745. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  41746. __decorate([
  41747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41748. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  41749. __decorate([
  41750. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  41751. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  41752. __decorate([
  41753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41754. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  41755. __decorate([
  41756. BABYLON.serializeAsColorCurves("cameraColorCurves")
  41757. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  41758. __decorate([
  41759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41760. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  41761. __decorate([
  41762. BABYLON.serialize()
  41763. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  41764. BABYLON.StandardMaterial = StandardMaterial;
  41765. })(BABYLON || (BABYLON = {}));
  41766. //# sourceMappingURL=babylon.standardMaterial.js.map
  41767. var BABYLON;
  41768. (function (BABYLON) {
  41769. /**
  41770. * This class implement a typical dictionary using a string as key and the generic type T as value.
  41771. * The underlying implementation relies on an associative array to ensure the best performances.
  41772. * The value can be anything including 'null' but except 'undefined'
  41773. */
  41774. var StringDictionary = (function () {
  41775. function StringDictionary() {
  41776. this._count = 0;
  41777. this._data = {};
  41778. }
  41779. /**
  41780. * This will clear this dictionary and copy the content from the 'source' one.
  41781. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  41782. * @param source the dictionary to take the content from and copy to this dictionary
  41783. */
  41784. StringDictionary.prototype.copyFrom = function (source) {
  41785. var _this = this;
  41786. this.clear();
  41787. source.forEach(function (t, v) { return _this.add(t, v); });
  41788. };
  41789. /**
  41790. * Get a value based from its key
  41791. * @param key the given key to get the matching value from
  41792. * @return the value if found, otherwise undefined is returned
  41793. */
  41794. StringDictionary.prototype.get = function (key) {
  41795. var val = this._data[key];
  41796. if (val !== undefined) {
  41797. return val;
  41798. }
  41799. return undefined;
  41800. };
  41801. /**
  41802. * Get a value from its key or add it if it doesn't exist.
  41803. * This method will ensure you that a given key/data will be present in the dictionary.
  41804. * @param key the given key to get the matching value from
  41805. * @param factory the factory that will create the value if the key is not present in the dictionary.
  41806. * The factory will only be invoked if there's no data for the given key.
  41807. * @return the value corresponding to the key.
  41808. */
  41809. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  41810. var val = this.get(key);
  41811. if (val !== undefined) {
  41812. return val;
  41813. }
  41814. val = factory(key);
  41815. if (val) {
  41816. this.add(key, val);
  41817. }
  41818. return val;
  41819. };
  41820. /**
  41821. * Get a value from its key if present in the dictionary otherwise add it
  41822. * @param key the key to get the value from
  41823. * @param val if there's no such key/value pair in the dictionary add it with this value
  41824. * @return the value corresponding to the key
  41825. */
  41826. StringDictionary.prototype.getOrAdd = function (key, val) {
  41827. var curVal = this.get(key);
  41828. if (curVal !== undefined) {
  41829. return curVal;
  41830. }
  41831. this.add(key, val);
  41832. return val;
  41833. };
  41834. /**
  41835. * Check if there's a given key in the dictionary
  41836. * @param key the key to check for
  41837. * @return true if the key is present, false otherwise
  41838. */
  41839. StringDictionary.prototype.contains = function (key) {
  41840. return this._data[key] !== undefined;
  41841. };
  41842. /**
  41843. * Add a new key and its corresponding value
  41844. * @param key the key to add
  41845. * @param value the value corresponding to the key
  41846. * @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
  41847. */
  41848. StringDictionary.prototype.add = function (key, value) {
  41849. if (this._data[key] !== undefined) {
  41850. return false;
  41851. }
  41852. this._data[key] = value;
  41853. ++this._count;
  41854. return true;
  41855. };
  41856. StringDictionary.prototype.set = function (key, value) {
  41857. if (this._data[key] === undefined) {
  41858. return false;
  41859. }
  41860. this._data[key] = value;
  41861. return true;
  41862. };
  41863. /**
  41864. * Get the element of the given key and remove it from the dictionary
  41865. * @param key
  41866. */
  41867. StringDictionary.prototype.getAndRemove = function (key) {
  41868. var val = this.get(key);
  41869. if (val !== undefined) {
  41870. delete this._data[key];
  41871. --this._count;
  41872. return val;
  41873. }
  41874. return null;
  41875. };
  41876. /**
  41877. * Remove a key/value from the dictionary.
  41878. * @param key the key to remove
  41879. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  41880. */
  41881. StringDictionary.prototype.remove = function (key) {
  41882. if (this.contains(key)) {
  41883. delete this._data[key];
  41884. --this._count;
  41885. return true;
  41886. }
  41887. return false;
  41888. };
  41889. /**
  41890. * Clear the whole content of the dictionary
  41891. */
  41892. StringDictionary.prototype.clear = function () {
  41893. this._data = {};
  41894. this._count = 0;
  41895. };
  41896. Object.defineProperty(StringDictionary.prototype, "count", {
  41897. get: function () {
  41898. return this._count;
  41899. },
  41900. enumerable: true,
  41901. configurable: true
  41902. });
  41903. /**
  41904. * Execute a callback on each key/val of the dictionary.
  41905. * Note that you can remove any element in this dictionary in the callback implementation
  41906. * @param callback the callback to execute on a given key/value pair
  41907. */
  41908. StringDictionary.prototype.forEach = function (callback) {
  41909. for (var cur in this._data) {
  41910. var val = this._data[cur];
  41911. callback(cur, val);
  41912. }
  41913. };
  41914. /**
  41915. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  41916. * If the callback returns null or undefined the method will iterate to the next key/value pair
  41917. * Note that you can remove any element in this dictionary in the callback implementation
  41918. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  41919. */
  41920. StringDictionary.prototype.first = function (callback) {
  41921. for (var cur in this._data) {
  41922. var val = this._data[cur];
  41923. var res = callback(cur, val);
  41924. if (res) {
  41925. return res;
  41926. }
  41927. }
  41928. return null;
  41929. };
  41930. return StringDictionary;
  41931. }());
  41932. BABYLON.StringDictionary = StringDictionary;
  41933. })(BABYLON || (BABYLON = {}));
  41934. //# sourceMappingURL=babylon.stringDictionary.js.map
  41935. var BABYLON;
  41936. (function (BABYLON) {
  41937. var DynamicFloatArrayElementInfo = (function () {
  41938. function DynamicFloatArrayElementInfo() {
  41939. }
  41940. return DynamicFloatArrayElementInfo;
  41941. }());
  41942. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  41943. /**
  41944. * 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.
  41945. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  41946. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  41947. * 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.
  41948. * 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.
  41949. * 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".
  41950. */
  41951. var DynamicFloatArray = (function () {
  41952. /**
  41953. * Construct an instance of the dynamic float array
  41954. * @param stride size of one element in float (i.e. not bytes!)
  41955. * @param initialElementCount the number of available entries at construction
  41956. */
  41957. function DynamicFloatArray(stride, initialElementCount) {
  41958. this.compareValueOffset = null;
  41959. this.sortingAscending = true;
  41960. this._stride = stride;
  41961. this.buffer = new Float32Array(stride * initialElementCount);
  41962. this._lastUsed = 0;
  41963. this._firstFree = 0;
  41964. this._allEntries = new Array(initialElementCount);
  41965. this._freeEntries = new Array(initialElementCount);
  41966. for (var i = 0; i < initialElementCount; i++) {
  41967. var element = new DynamicFloatArrayElementInfo();
  41968. element.offset = i * stride;
  41969. this._allEntries[i] = element;
  41970. this._freeEntries[initialElementCount - i - 1] = element;
  41971. }
  41972. }
  41973. /**
  41974. * Allocate an element in the array.
  41975. * @return the element info instance that contains the offset into the main buffer of the element's location.
  41976. * Beware, this offset may change when you call pack()
  41977. */
  41978. DynamicFloatArray.prototype.allocElement = function () {
  41979. if (this._freeEntries.length === 0) {
  41980. this._growBuffer();
  41981. }
  41982. var el = this._freeEntries.pop();
  41983. this._lastUsed = Math.max(el.offset, this._lastUsed);
  41984. if (el.offset === this._firstFree) {
  41985. if (this._freeEntries.length > 0) {
  41986. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  41987. }
  41988. else {
  41989. this._firstFree += this._stride;
  41990. }
  41991. }
  41992. return el;
  41993. };
  41994. /**
  41995. * Free the element corresponding to the given element info
  41996. * @param elInfo the element that describe the allocated element
  41997. */
  41998. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  41999. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  42000. this._freeEntries.push(elInfo);
  42001. };
  42002. /**
  42003. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  42004. * 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().
  42005. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  42006. */
  42007. DynamicFloatArray.prototype.pack = function () {
  42008. // no free slot? no need to pack
  42009. if (this._freeEntries.length === 0) {
  42010. return this.buffer;
  42011. }
  42012. // If the buffer is already packed the last used will always be lower than the first free
  42013. // 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.
  42014. if (this._lastUsed < this._firstFree) {
  42015. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  42016. return elementsBuffer_1;
  42017. }
  42018. var s = this._stride;
  42019. // 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
  42020. var lastFree = new DynamicFloatArrayElementInfo();
  42021. lastFree.offset = this.totalElementCount * s;
  42022. this._freeEntries.push(lastFree);
  42023. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  42024. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  42025. var firstFreeSlotOffset = sortedFree[0].offset;
  42026. var freeZoneSize = 1;
  42027. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  42028. var prevOffset = sortedFree[0].offset;
  42029. for (var i = 1; i < sortedFree.length; i++) {
  42030. // 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
  42031. if (firstFreeSlotOffset >= occupiedZoneSize) {
  42032. break;
  42033. }
  42034. var curFree = sortedFree[i];
  42035. var curOffset = curFree.offset;
  42036. // Compute the distance between this offset and the previous
  42037. var distance = curOffset - prevOffset;
  42038. // If the distance is the stride size, they are adjacent, it good, move to the next
  42039. if (distance === s) {
  42040. // Free zone is one element bigger
  42041. ++freeZoneSize;
  42042. // as we're about to iterate to the next, the cur becomes the previous...
  42043. prevOffset = curOffset;
  42044. continue;
  42045. }
  42046. // Distance is bigger, which means there's x element between the previous free and this one
  42047. var usedRange = (distance / s) - 1;
  42048. // Two cases the free zone is smaller than the data to move or bigger
  42049. // Copy what can fit in the free zone
  42050. var curMoveOffset = curOffset - s;
  42051. var copyCount = Math.min(freeZoneSize, usedRange);
  42052. for (var j = 0; j < copyCount; j++) {
  42053. var freeI = firstFreeSlotOffset / s;
  42054. var curI = curMoveOffset / s;
  42055. var moveEl = sortedAll[curI];
  42056. this._moveElement(moveEl, firstFreeSlotOffset);
  42057. var replacedEl = sortedAll[freeI];
  42058. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  42059. replacedEl.offset = curMoveOffset;
  42060. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  42061. sortedAll[freeI] = moveEl;
  42062. sortedAll[curI] = replacedEl;
  42063. curMoveOffset -= s;
  42064. firstFreeSlotOffset += s;
  42065. }
  42066. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  42067. if (freeZoneSize <= usedRange) {
  42068. firstFreeSlotOffset = curMoveOffset + s;
  42069. freeZoneSize = 1 + copyCount;
  42070. }
  42071. else {
  42072. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  42073. }
  42074. // as we're about to iterate to the next, the cur becomes the previous...
  42075. prevOffset = curOffset;
  42076. }
  42077. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  42078. this._lastUsed = firstFreeSlotOffset - s;
  42079. this._firstFree = firstFreeSlotOffset;
  42080. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  42081. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  42082. this._allEntries = sortedAll;
  42083. return elementsBuffer;
  42084. };
  42085. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  42086. for (var i = 0; i < this._stride; i++) {
  42087. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  42088. }
  42089. element.offset = destOffset;
  42090. };
  42091. DynamicFloatArray.prototype._growBuffer = function () {
  42092. // Allocate the new buffer with 50% more entries, copy the content of the current one
  42093. var newElCount = Math.floor(this.totalElementCount * 1.5);
  42094. var newBuffer = new Float32Array(newElCount * this._stride);
  42095. newBuffer.set(this.buffer);
  42096. var curCount = this.totalElementCount;
  42097. var addedCount = newElCount - this.totalElementCount;
  42098. for (var i = 0; i < addedCount; i++) {
  42099. var element = new DynamicFloatArrayElementInfo();
  42100. element.offset = (curCount + i) * this.stride;
  42101. this._allEntries.push(element);
  42102. this._freeEntries[addedCount - i - 1] = element;
  42103. }
  42104. this._firstFree = curCount * this.stride;
  42105. this.buffer = newBuffer;
  42106. };
  42107. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  42108. /**
  42109. * Get the total count of entries that can fit in the current buffer
  42110. * @returns the elements count
  42111. */
  42112. get: function () {
  42113. return this._allEntries.length;
  42114. },
  42115. enumerable: true,
  42116. configurable: true
  42117. });
  42118. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  42119. /**
  42120. * Get the count of free entries that can still be allocated without resizing the buffer
  42121. * @returns the free elements count
  42122. */
  42123. get: function () {
  42124. return this._freeEntries.length;
  42125. },
  42126. enumerable: true,
  42127. configurable: true
  42128. });
  42129. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  42130. /**
  42131. * Get the count of allocated elements
  42132. * @returns the allocated elements count
  42133. */
  42134. get: function () {
  42135. return this._allEntries.length - this._freeEntries.length;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  42141. /**
  42142. * Return the size of one element in float
  42143. * @returns the size in float
  42144. */
  42145. get: function () {
  42146. return this._stride;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. DynamicFloatArray.prototype.sort = function () {
  42152. var _this = this;
  42153. if (!this.compareValueOffset) {
  42154. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  42155. }
  42156. var count = this.usedElementCount;
  42157. // Do we have to (re)create the sort table?
  42158. if (!this._sortTable || this._sortTable.length < count) {
  42159. // 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...
  42160. var newCount = Math.min(this.totalElementCount, count * 2);
  42161. this._sortTable = new Array(newCount);
  42162. }
  42163. if (!this._sortedTable || this._sortedTable.length !== count) {
  42164. this._sortedTable = new Array(count);
  42165. }
  42166. // Because, you know...
  42167. this.pack();
  42168. //let stride = this.stride;
  42169. //for (let i = 0; i < count; i++) {
  42170. // let si = this._sortTable[i];
  42171. // if (!si) {
  42172. // si = new SortInfo();
  42173. // this._sortTable[i] = si;
  42174. // }
  42175. // si.entry = this._allEntries[i];
  42176. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  42177. // si.swapedOffset = null;
  42178. // this._sortedTable[i] = si;
  42179. //}
  42180. var curOffset = 0;
  42181. var stride = this.stride;
  42182. for (var i = 0; i < count; i++, curOffset += stride) {
  42183. var si = this._sortTable[i];
  42184. if (!si) {
  42185. si = new SortInfo();
  42186. this._sortTable[i] = si;
  42187. }
  42188. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  42189. si.offset = curOffset;
  42190. si.swapedOffset = null;
  42191. this._sortedTable[i] = si;
  42192. }
  42193. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  42194. if (this.sortingAscending) {
  42195. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  42196. }
  42197. else {
  42198. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  42199. }
  42200. var swapElements = function (src, dst) {
  42201. for (var i = 0; i < stride; i++) {
  42202. var tps = _this.buffer[dst + i];
  42203. _this.buffer[dst + i] = _this.buffer[src + i];
  42204. _this.buffer[src + i] = tps;
  42205. }
  42206. };
  42207. // 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:
  42208. // 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),
  42209. // and I still want something with a good algorithm complexity.
  42210. // 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,
  42211. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  42212. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  42213. // 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
  42214. // until we find a SortInfo object without a swapedOffset which means we got the right location
  42215. // 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
  42216. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  42217. for (var i = 0; i < count; i++) {
  42218. // Get the element to move
  42219. var sourceSI = this._sortedTable[i];
  42220. var destSI = this._sortTable[i];
  42221. var sourceOff = sourceSI.offset;
  42222. // If the source changed location, find the new one
  42223. if (sourceSI.swapedOffset) {
  42224. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  42225. var curSI = sourceSI;
  42226. while (curSI.swapedOffset) {
  42227. curSI = this._sortTable[curSI.swapedOffset / stride];
  42228. }
  42229. // Finally get the right location
  42230. sourceOff = curSI.offset;
  42231. }
  42232. // Tag the element being replaced with its new location
  42233. destSI.swapedOffset = sourceOff;
  42234. // Swap elements (only if needed)
  42235. if (sourceOff !== destSI.offset) {
  42236. swapElements(sourceOff, destSI.offset);
  42237. }
  42238. // Update the offset in the corresponding DFAE
  42239. //sourceSI.entry.offset = destSI.entry.offset;
  42240. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  42241. }
  42242. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  42243. return true;
  42244. };
  42245. return DynamicFloatArray;
  42246. }());
  42247. BABYLON.DynamicFloatArray = DynamicFloatArray;
  42248. var SortInfo = (function () {
  42249. function SortInfo() {
  42250. this.compareData = this.offset = this.swapedOffset = null;
  42251. }
  42252. return SortInfo;
  42253. }());
  42254. })(BABYLON || (BABYLON = {}));
  42255. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  42256. var BABYLON;
  42257. (function (BABYLON) {
  42258. var Condition = (function () {
  42259. function Condition(actionManager) {
  42260. this._actionManager = actionManager;
  42261. }
  42262. Condition.prototype.isValid = function () {
  42263. return true;
  42264. };
  42265. Condition.prototype._getProperty = function (propertyPath) {
  42266. return this._actionManager._getProperty(propertyPath);
  42267. };
  42268. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42269. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42270. };
  42271. Condition.prototype.serialize = function () {
  42272. };
  42273. Condition.prototype._serialize = function (serializedCondition) {
  42274. return {
  42275. type: 2,
  42276. children: [],
  42277. name: serializedCondition.name,
  42278. properties: serializedCondition.properties
  42279. };
  42280. };
  42281. return Condition;
  42282. }());
  42283. BABYLON.Condition = Condition;
  42284. var ValueCondition = (function (_super) {
  42285. __extends(ValueCondition, _super);
  42286. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42287. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42288. var _this = _super.call(this, actionManager) || this;
  42289. _this.propertyPath = propertyPath;
  42290. _this.value = value;
  42291. _this.operator = operator;
  42292. _this._target = target;
  42293. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42294. _this._property = _this._getProperty(_this.propertyPath);
  42295. return _this;
  42296. }
  42297. Object.defineProperty(ValueCondition, "IsEqual", {
  42298. get: function () {
  42299. return ValueCondition._IsEqual;
  42300. },
  42301. enumerable: true,
  42302. configurable: true
  42303. });
  42304. Object.defineProperty(ValueCondition, "IsDifferent", {
  42305. get: function () {
  42306. return ValueCondition._IsDifferent;
  42307. },
  42308. enumerable: true,
  42309. configurable: true
  42310. });
  42311. Object.defineProperty(ValueCondition, "IsGreater", {
  42312. get: function () {
  42313. return ValueCondition._IsGreater;
  42314. },
  42315. enumerable: true,
  42316. configurable: true
  42317. });
  42318. Object.defineProperty(ValueCondition, "IsLesser", {
  42319. get: function () {
  42320. return ValueCondition._IsLesser;
  42321. },
  42322. enumerable: true,
  42323. configurable: true
  42324. });
  42325. // Methods
  42326. ValueCondition.prototype.isValid = function () {
  42327. switch (this.operator) {
  42328. case ValueCondition.IsGreater:
  42329. return this._effectiveTarget[this._property] > this.value;
  42330. case ValueCondition.IsLesser:
  42331. return this._effectiveTarget[this._property] < this.value;
  42332. case ValueCondition.IsEqual:
  42333. case ValueCondition.IsDifferent:
  42334. var check;
  42335. if (this.value.equals) {
  42336. check = this.value.equals(this._effectiveTarget[this._property]);
  42337. }
  42338. else {
  42339. check = this.value === this._effectiveTarget[this._property];
  42340. }
  42341. return this.operator === ValueCondition.IsEqual ? check : !check;
  42342. }
  42343. return false;
  42344. };
  42345. ValueCondition.prototype.serialize = function () {
  42346. return this._serialize({
  42347. name: "ValueCondition",
  42348. properties: [
  42349. BABYLON.Action._GetTargetProperty(this._target),
  42350. { name: "propertyPath", value: this.propertyPath },
  42351. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42352. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42353. ]
  42354. });
  42355. };
  42356. ValueCondition.GetOperatorName = function (operator) {
  42357. switch (operator) {
  42358. case ValueCondition._IsEqual: return "IsEqual";
  42359. case ValueCondition._IsDifferent: return "IsDifferent";
  42360. case ValueCondition._IsGreater: return "IsGreater";
  42361. case ValueCondition._IsLesser: return "IsLesser";
  42362. default: return "";
  42363. }
  42364. };
  42365. return ValueCondition;
  42366. }(Condition));
  42367. // Statics
  42368. ValueCondition._IsEqual = 0;
  42369. ValueCondition._IsDifferent = 1;
  42370. ValueCondition._IsGreater = 2;
  42371. ValueCondition._IsLesser = 3;
  42372. BABYLON.ValueCondition = ValueCondition;
  42373. var PredicateCondition = (function (_super) {
  42374. __extends(PredicateCondition, _super);
  42375. function PredicateCondition(actionManager, predicate) {
  42376. var _this = _super.call(this, actionManager) || this;
  42377. _this.predicate = predicate;
  42378. return _this;
  42379. }
  42380. PredicateCondition.prototype.isValid = function () {
  42381. return this.predicate();
  42382. };
  42383. return PredicateCondition;
  42384. }(Condition));
  42385. BABYLON.PredicateCondition = PredicateCondition;
  42386. var StateCondition = (function (_super) {
  42387. __extends(StateCondition, _super);
  42388. function StateCondition(actionManager, target, value) {
  42389. var _this = _super.call(this, actionManager) || this;
  42390. _this.value = value;
  42391. _this._target = target;
  42392. return _this;
  42393. }
  42394. // Methods
  42395. StateCondition.prototype.isValid = function () {
  42396. return this._target.state === this.value;
  42397. };
  42398. StateCondition.prototype.serialize = function () {
  42399. return this._serialize({
  42400. name: "StateCondition",
  42401. properties: [
  42402. BABYLON.Action._GetTargetProperty(this._target),
  42403. { name: "value", value: this.value }
  42404. ]
  42405. });
  42406. };
  42407. return StateCondition;
  42408. }(Condition));
  42409. BABYLON.StateCondition = StateCondition;
  42410. })(BABYLON || (BABYLON = {}));
  42411. //# sourceMappingURL=babylon.condition.js.map
  42412. var BABYLON;
  42413. (function (BABYLON) {
  42414. var Action = (function () {
  42415. function Action(triggerOptions, condition) {
  42416. this.triggerOptions = triggerOptions;
  42417. if (triggerOptions.parameter) {
  42418. this.trigger = triggerOptions.trigger;
  42419. this._triggerParameter = triggerOptions.parameter;
  42420. }
  42421. else {
  42422. this.trigger = triggerOptions;
  42423. }
  42424. this._nextActiveAction = this;
  42425. this._condition = condition;
  42426. }
  42427. // Methods
  42428. Action.prototype._prepare = function () {
  42429. };
  42430. Action.prototype.getTriggerParameter = function () {
  42431. return this._triggerParameter;
  42432. };
  42433. Action.prototype._executeCurrent = function (evt) {
  42434. if (this._nextActiveAction._condition) {
  42435. var condition = this._nextActiveAction._condition;
  42436. var currentRenderId = this._actionManager.getScene().getRenderId();
  42437. // We cache the current evaluation for the current frame
  42438. if (condition._evaluationId === currentRenderId) {
  42439. if (!condition._currentResult) {
  42440. return;
  42441. }
  42442. }
  42443. else {
  42444. condition._evaluationId = currentRenderId;
  42445. if (!condition.isValid()) {
  42446. condition._currentResult = false;
  42447. return;
  42448. }
  42449. condition._currentResult = true;
  42450. }
  42451. }
  42452. this._nextActiveAction.execute(evt);
  42453. this.skipToNextActiveAction();
  42454. };
  42455. Action.prototype.execute = function (evt) {
  42456. };
  42457. Action.prototype.skipToNextActiveAction = function () {
  42458. if (this._nextActiveAction._child) {
  42459. if (!this._nextActiveAction._child._actionManager) {
  42460. this._nextActiveAction._child._actionManager = this._actionManager;
  42461. }
  42462. this._nextActiveAction = this._nextActiveAction._child;
  42463. }
  42464. else {
  42465. this._nextActiveAction = this;
  42466. }
  42467. };
  42468. Action.prototype.then = function (action) {
  42469. this._child = action;
  42470. action._actionManager = this._actionManager;
  42471. action._prepare();
  42472. return action;
  42473. };
  42474. Action.prototype._getProperty = function (propertyPath) {
  42475. return this._actionManager._getProperty(propertyPath);
  42476. };
  42477. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42478. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42479. };
  42480. Action.prototype.serialize = function (parent) {
  42481. };
  42482. // Called by BABYLON.Action objects in serialize(...). Internal use
  42483. Action.prototype._serialize = function (serializedAction, parent) {
  42484. var serializationObject = {
  42485. type: 1,
  42486. children: [],
  42487. name: serializedAction.name,
  42488. properties: serializedAction.properties || []
  42489. };
  42490. // Serialize child
  42491. if (this._child) {
  42492. this._child.serialize(serializationObject);
  42493. }
  42494. // Check if "this" has a condition
  42495. if (this._condition) {
  42496. var serializedCondition = this._condition.serialize();
  42497. serializedCondition.children.push(serializationObject);
  42498. if (parent) {
  42499. parent.children.push(serializedCondition);
  42500. }
  42501. return serializedCondition;
  42502. }
  42503. if (parent) {
  42504. parent.children.push(serializationObject);
  42505. }
  42506. return serializationObject;
  42507. };
  42508. return Action;
  42509. }());
  42510. Action._SerializeValueAsString = function (value) {
  42511. if (typeof value === "number") {
  42512. return value.toString();
  42513. }
  42514. if (typeof value === "boolean") {
  42515. return value ? "true" : "false";
  42516. }
  42517. if (value instanceof BABYLON.Vector2) {
  42518. return value.x + ", " + value.y;
  42519. }
  42520. if (value instanceof BABYLON.Vector3) {
  42521. return value.x + ", " + value.y + ", " + value.z;
  42522. }
  42523. if (value instanceof BABYLON.Color3) {
  42524. return value.r + ", " + value.g + ", " + value.b;
  42525. }
  42526. if (value instanceof BABYLON.Color4) {
  42527. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42528. }
  42529. return value; // string
  42530. };
  42531. Action._GetTargetProperty = function (target) {
  42532. return {
  42533. name: "target",
  42534. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42535. : target instanceof BABYLON.Light ? "LightProperties"
  42536. : target instanceof BABYLON.Camera ? "CameraProperties"
  42537. : "SceneProperties",
  42538. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42539. };
  42540. };
  42541. BABYLON.Action = Action;
  42542. })(BABYLON || (BABYLON = {}));
  42543. //# sourceMappingURL=babylon.action.js.map
  42544. var BABYLON;
  42545. (function (BABYLON) {
  42546. /**
  42547. * ActionEvent is the event beint sent when an action is triggered.
  42548. */
  42549. var ActionEvent = (function () {
  42550. /**
  42551. * @constructor
  42552. * @param source The mesh or sprite that triggered the action.
  42553. * @param pointerX The X mouse cursor position at the time of the event
  42554. * @param pointerY The Y mouse cursor position at the time of the event
  42555. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42556. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42557. */
  42558. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42559. this.source = source;
  42560. this.pointerX = pointerX;
  42561. this.pointerY = pointerY;
  42562. this.meshUnderPointer = meshUnderPointer;
  42563. this.sourceEvent = sourceEvent;
  42564. this.additionalData = additionalData;
  42565. }
  42566. /**
  42567. * Helper function to auto-create an ActionEvent from a source mesh.
  42568. * @param source The source mesh that triggered the event
  42569. * @param evt {Event} The original (browser) event
  42570. */
  42571. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42572. var scene = source.getScene();
  42573. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42574. };
  42575. /**
  42576. * Helper function to auto-create an ActionEvent from a source mesh.
  42577. * @param source The source sprite that triggered the event
  42578. * @param scene Scene associated with the sprite
  42579. * @param evt {Event} The original (browser) event
  42580. */
  42581. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42582. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42583. };
  42584. /**
  42585. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42586. * @param scene the scene where the event occurred
  42587. * @param evt {Event} The original (browser) event
  42588. */
  42589. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42590. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42591. };
  42592. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42593. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42594. };
  42595. return ActionEvent;
  42596. }());
  42597. BABYLON.ActionEvent = ActionEvent;
  42598. /**
  42599. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42600. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42601. */
  42602. var ActionManager = (function () {
  42603. function ActionManager(scene) {
  42604. // Members
  42605. this.actions = new Array();
  42606. this.hoverCursor = '';
  42607. this._scene = scene;
  42608. scene._actionManagers.push(this);
  42609. }
  42610. Object.defineProperty(ActionManager, "NothingTrigger", {
  42611. get: function () {
  42612. return ActionManager._NothingTrigger;
  42613. },
  42614. enumerable: true,
  42615. configurable: true
  42616. });
  42617. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42618. get: function () {
  42619. return ActionManager._OnPickTrigger;
  42620. },
  42621. enumerable: true,
  42622. configurable: true
  42623. });
  42624. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42625. get: function () {
  42626. return ActionManager._OnLeftPickTrigger;
  42627. },
  42628. enumerable: true,
  42629. configurable: true
  42630. });
  42631. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42632. get: function () {
  42633. return ActionManager._OnRightPickTrigger;
  42634. },
  42635. enumerable: true,
  42636. configurable: true
  42637. });
  42638. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42639. get: function () {
  42640. return ActionManager._OnCenterPickTrigger;
  42641. },
  42642. enumerable: true,
  42643. configurable: true
  42644. });
  42645. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42646. get: function () {
  42647. return ActionManager._OnPickDownTrigger;
  42648. },
  42649. enumerable: true,
  42650. configurable: true
  42651. });
  42652. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42653. get: function () {
  42654. return ActionManager._OnDoublePickTrigger;
  42655. },
  42656. enumerable: true,
  42657. configurable: true
  42658. });
  42659. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42660. get: function () {
  42661. return ActionManager._OnPickUpTrigger;
  42662. },
  42663. enumerable: true,
  42664. configurable: true
  42665. });
  42666. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42667. /// This trigger will only be raised if you also declared a OnPickDown
  42668. get: function () {
  42669. return ActionManager._OnPickOutTrigger;
  42670. },
  42671. enumerable: true,
  42672. configurable: true
  42673. });
  42674. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42675. get: function () {
  42676. return ActionManager._OnLongPressTrigger;
  42677. },
  42678. enumerable: true,
  42679. configurable: true
  42680. });
  42681. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42682. get: function () {
  42683. return ActionManager._OnPointerOverTrigger;
  42684. },
  42685. enumerable: true,
  42686. configurable: true
  42687. });
  42688. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42689. get: function () {
  42690. return ActionManager._OnPointerOutTrigger;
  42691. },
  42692. enumerable: true,
  42693. configurable: true
  42694. });
  42695. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42696. get: function () {
  42697. return ActionManager._OnEveryFrameTrigger;
  42698. },
  42699. enumerable: true,
  42700. configurable: true
  42701. });
  42702. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42703. get: function () {
  42704. return ActionManager._OnIntersectionEnterTrigger;
  42705. },
  42706. enumerable: true,
  42707. configurable: true
  42708. });
  42709. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42710. get: function () {
  42711. return ActionManager._OnIntersectionExitTrigger;
  42712. },
  42713. enumerable: true,
  42714. configurable: true
  42715. });
  42716. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42717. get: function () {
  42718. return ActionManager._OnKeyDownTrigger;
  42719. },
  42720. enumerable: true,
  42721. configurable: true
  42722. });
  42723. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42724. get: function () {
  42725. return ActionManager._OnKeyUpTrigger;
  42726. },
  42727. enumerable: true,
  42728. configurable: true
  42729. });
  42730. // Methods
  42731. ActionManager.prototype.dispose = function () {
  42732. var index = this._scene._actionManagers.indexOf(this);
  42733. for (var i = 0; i < this.actions.length; i++) {
  42734. var action = this.actions[i];
  42735. ActionManager.Triggers[action.trigger]--;
  42736. if (ActionManager.Triggers[action.trigger] === 0) {
  42737. delete ActionManager.Triggers[action.trigger];
  42738. }
  42739. }
  42740. if (index > -1) {
  42741. this._scene._actionManagers.splice(index, 1);
  42742. }
  42743. };
  42744. ActionManager.prototype.getScene = function () {
  42745. return this._scene;
  42746. };
  42747. /**
  42748. * Does this action manager handles actions of any of the given triggers
  42749. * @param {number[]} triggers - the triggers to be tested
  42750. * @return {boolean} whether one (or more) of the triggers is handeled
  42751. */
  42752. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42753. for (var index = 0; index < this.actions.length; index++) {
  42754. var action = this.actions[index];
  42755. if (triggers.indexOf(action.trigger) > -1) {
  42756. return true;
  42757. }
  42758. }
  42759. return false;
  42760. };
  42761. /**
  42762. * Does this action manager handles actions of a given trigger
  42763. * @param {number} trigger - the trigger to be tested
  42764. * @return {boolean} whether the trigger is handeled
  42765. */
  42766. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42767. for (var index = 0; index < this.actions.length; index++) {
  42768. var action = this.actions[index];
  42769. if (action.trigger === trigger) {
  42770. return true;
  42771. }
  42772. }
  42773. return false;
  42774. };
  42775. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42776. /**
  42777. * Does this action manager has pointer triggers
  42778. * @return {boolean} whether or not it has pointer triggers
  42779. */
  42780. get: function () {
  42781. for (var index = 0; index < this.actions.length; index++) {
  42782. var action = this.actions[index];
  42783. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42784. return true;
  42785. }
  42786. }
  42787. return false;
  42788. },
  42789. enumerable: true,
  42790. configurable: true
  42791. });
  42792. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42793. /**
  42794. * Does this action manager has pick triggers
  42795. * @return {boolean} whether or not it has pick triggers
  42796. */
  42797. get: function () {
  42798. for (var index = 0; index < this.actions.length; index++) {
  42799. var action = this.actions[index];
  42800. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42801. return true;
  42802. }
  42803. }
  42804. return false;
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(ActionManager, "HasTriggers", {
  42810. /**
  42811. * Does exist one action manager with at least one trigger
  42812. * @return {boolean} whether or not it exists one action manager with one trigger
  42813. **/
  42814. get: function () {
  42815. for (var t in ActionManager.Triggers) {
  42816. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42817. return true;
  42818. }
  42819. }
  42820. return false;
  42821. },
  42822. enumerable: true,
  42823. configurable: true
  42824. });
  42825. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42826. /**
  42827. * Does exist one action manager with at least one pick trigger
  42828. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42829. **/
  42830. get: function () {
  42831. for (var t in ActionManager.Triggers) {
  42832. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42833. var t_int = parseInt(t);
  42834. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42835. return true;
  42836. }
  42837. }
  42838. }
  42839. return false;
  42840. },
  42841. enumerable: true,
  42842. configurable: true
  42843. });
  42844. /**
  42845. * Does exist one action manager that handles actions of a given trigger
  42846. * @param {number} trigger - the trigger to be tested
  42847. * @return {boolean} whether the trigger is handeled by at least one action manager
  42848. **/
  42849. ActionManager.HasSpecificTrigger = function (trigger) {
  42850. for (var t in ActionManager.Triggers) {
  42851. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42852. var t_int = parseInt(t);
  42853. if (t_int === trigger) {
  42854. return true;
  42855. }
  42856. }
  42857. }
  42858. return false;
  42859. };
  42860. /**
  42861. * Registers an action to this action manager
  42862. * @param {BABYLON.Action} action - the action to be registered
  42863. * @return {BABYLON.Action} the action amended (prepared) after registration
  42864. */
  42865. ActionManager.prototype.registerAction = function (action) {
  42866. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42867. if (this.getScene().actionManager !== this) {
  42868. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42869. return null;
  42870. }
  42871. }
  42872. this.actions.push(action);
  42873. if (ActionManager.Triggers[action.trigger]) {
  42874. ActionManager.Triggers[action.trigger]++;
  42875. }
  42876. else {
  42877. ActionManager.Triggers[action.trigger] = 1;
  42878. }
  42879. action._actionManager = this;
  42880. action._prepare();
  42881. return action;
  42882. };
  42883. /**
  42884. * Process a specific trigger
  42885. * @param {number} trigger - the trigger to process
  42886. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42887. */
  42888. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42889. for (var index = 0; index < this.actions.length; index++) {
  42890. var action = this.actions[index];
  42891. if (action.trigger === trigger) {
  42892. if (trigger === ActionManager.OnKeyUpTrigger
  42893. || trigger === ActionManager.OnKeyDownTrigger) {
  42894. var parameter = action.getTriggerParameter();
  42895. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42896. if (!parameter.toLowerCase) {
  42897. continue;
  42898. }
  42899. var lowerCase = parameter.toLowerCase();
  42900. if (lowerCase !== evt.sourceEvent.key) {
  42901. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42902. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42903. if (actualkey !== lowerCase) {
  42904. continue;
  42905. }
  42906. }
  42907. }
  42908. }
  42909. action._executeCurrent(evt);
  42910. }
  42911. }
  42912. };
  42913. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42914. var properties = propertyPath.split(".");
  42915. for (var index = 0; index < properties.length - 1; index++) {
  42916. target = target[properties[index]];
  42917. }
  42918. return target;
  42919. };
  42920. ActionManager.prototype._getProperty = function (propertyPath) {
  42921. var properties = propertyPath.split(".");
  42922. return properties[properties.length - 1];
  42923. };
  42924. ActionManager.prototype.serialize = function (name) {
  42925. var root = {
  42926. children: [],
  42927. name: name,
  42928. type: 3,
  42929. properties: [] // Empty for root but required
  42930. };
  42931. for (var i = 0; i < this.actions.length; i++) {
  42932. var triggerObject = {
  42933. type: 0,
  42934. children: [],
  42935. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42936. properties: []
  42937. };
  42938. var triggerOptions = this.actions[i].triggerOptions;
  42939. if (triggerOptions && typeof triggerOptions !== "number") {
  42940. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42941. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42942. }
  42943. else {
  42944. var parameter = {};
  42945. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42946. if (triggerOptions.parameter.mesh) {
  42947. parameter._meshId = triggerOptions.parameter.mesh.id;
  42948. }
  42949. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42950. }
  42951. }
  42952. // Serialize child action, recursively
  42953. this.actions[i].serialize(triggerObject);
  42954. // Add serialized trigger
  42955. root.children.push(triggerObject);
  42956. }
  42957. return root;
  42958. };
  42959. ActionManager.Parse = function (parsedActions, object, scene) {
  42960. var actionManager = new BABYLON.ActionManager(scene);
  42961. if (object === null)
  42962. scene.actionManager = actionManager;
  42963. else
  42964. object.actionManager = actionManager;
  42965. // instanciate a new object
  42966. var instanciate = function (name, params) {
  42967. var newInstance = Object.create(BABYLON[name].prototype);
  42968. newInstance.constructor.apply(newInstance, params);
  42969. return newInstance;
  42970. };
  42971. var parseParameter = function (name, value, target, propertyPath) {
  42972. if (propertyPath === null) {
  42973. // String, boolean or float
  42974. var floatValue = parseFloat(value);
  42975. if (value === "true" || value === "false")
  42976. return value === "true";
  42977. else
  42978. return isNaN(floatValue) ? value : floatValue;
  42979. }
  42980. var effectiveTarget = propertyPath.split(".");
  42981. var values = value.split(",");
  42982. // Get effective Target
  42983. for (var i = 0; i < effectiveTarget.length; i++) {
  42984. target = target[effectiveTarget[i]];
  42985. }
  42986. // Return appropriate value with its type
  42987. if (typeof (target) === "boolean")
  42988. return values[0] === "true";
  42989. if (typeof (target) === "string")
  42990. return values[0];
  42991. // Parameters with multiple values such as Vector3 etc.
  42992. var split = new Array();
  42993. for (var i = 0; i < values.length; i++)
  42994. split.push(parseFloat(values[i]));
  42995. if (target instanceof BABYLON.Vector3)
  42996. return BABYLON.Vector3.FromArray(split);
  42997. if (target instanceof BABYLON.Vector4)
  42998. return BABYLON.Vector4.FromArray(split);
  42999. if (target instanceof BABYLON.Color3)
  43000. return BABYLON.Color3.FromArray(split);
  43001. if (target instanceof BABYLON.Color4)
  43002. return BABYLON.Color4.FromArray(split);
  43003. return parseFloat(values[0]);
  43004. };
  43005. // traverse graph per trigger
  43006. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43007. if (combineArray === void 0) { combineArray = null; }
  43008. if (parsedAction.detached)
  43009. return;
  43010. var parameters = new Array();
  43011. var target = null;
  43012. var propertyPath = null;
  43013. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43014. // Parameters
  43015. if (parsedAction.type === 2)
  43016. parameters.push(actionManager);
  43017. else
  43018. parameters.push(trigger);
  43019. if (combine) {
  43020. var actions = new Array();
  43021. for (var j = 0; j < parsedAction.combine.length; j++) {
  43022. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43023. }
  43024. parameters.push(actions);
  43025. }
  43026. else {
  43027. for (var i = 0; i < parsedAction.properties.length; i++) {
  43028. var value = parsedAction.properties[i].value;
  43029. var name = parsedAction.properties[i].name;
  43030. var targetType = parsedAction.properties[i].targetType;
  43031. if (name === "target")
  43032. if (targetType !== null && targetType === "SceneProperties")
  43033. value = target = scene;
  43034. else
  43035. value = target = scene.getNodeByName(value);
  43036. else if (name === "parent")
  43037. value = scene.getNodeByName(value);
  43038. else if (name === "sound")
  43039. value = scene.getSoundByName(value);
  43040. else if (name !== "propertyPath") {
  43041. if (parsedAction.type === 2 && name === "operator")
  43042. value = BABYLON.ValueCondition[value];
  43043. else
  43044. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43045. }
  43046. else {
  43047. propertyPath = value;
  43048. }
  43049. parameters.push(value);
  43050. }
  43051. }
  43052. if (combineArray === null) {
  43053. parameters.push(condition);
  43054. }
  43055. else {
  43056. parameters.push(null);
  43057. }
  43058. // If interpolate value action
  43059. if (parsedAction.name === "InterpolateValueAction") {
  43060. var param = parameters[parameters.length - 2];
  43061. parameters[parameters.length - 1] = param;
  43062. parameters[parameters.length - 2] = condition;
  43063. }
  43064. // Action or condition(s) and not CombineAction
  43065. var newAction = instanciate(parsedAction.name, parameters);
  43066. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43067. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43068. if (action)
  43069. action.then(nothing);
  43070. else
  43071. actionManager.registerAction(nothing);
  43072. action = nothing;
  43073. }
  43074. if (combineArray === null) {
  43075. if (newAction instanceof BABYLON.Condition) {
  43076. condition = newAction;
  43077. newAction = action;
  43078. }
  43079. else {
  43080. condition = null;
  43081. if (action)
  43082. action.then(newAction);
  43083. else
  43084. actionManager.registerAction(newAction);
  43085. }
  43086. }
  43087. else {
  43088. combineArray.push(newAction);
  43089. }
  43090. for (var i = 0; i < parsedAction.children.length; i++)
  43091. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43092. };
  43093. // triggers
  43094. for (var i = 0; i < parsedActions.children.length; i++) {
  43095. var triggerParams;
  43096. var trigger = parsedActions.children[i];
  43097. if (trigger.properties.length > 0) {
  43098. var param = trigger.properties[0].value;
  43099. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43100. if (value._meshId) {
  43101. value.mesh = scene.getMeshByID(value._meshId);
  43102. }
  43103. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  43104. }
  43105. else
  43106. triggerParams = BABYLON.ActionManager[trigger.name];
  43107. for (var j = 0; j < trigger.children.length; j++) {
  43108. if (!trigger.detached)
  43109. traverse(trigger.children[j], triggerParams, null, null);
  43110. }
  43111. }
  43112. };
  43113. ActionManager.GetTriggerName = function (trigger) {
  43114. switch (trigger) {
  43115. case 0: return "NothingTrigger";
  43116. case 1: return "OnPickTrigger";
  43117. case 2: return "OnLeftPickTrigger";
  43118. case 3: return "OnRightPickTrigger";
  43119. case 4: return "OnCenterPickTrigger";
  43120. case 5: return "OnPickDownTrigger";
  43121. case 6: return "OnPickUpTrigger";
  43122. case 7: return "OnLongPressTrigger";
  43123. case 8: return "OnPointerOverTrigger";
  43124. case 9: return "OnPointerOutTrigger";
  43125. case 10: return "OnEveryFrameTrigger";
  43126. case 11: return "OnIntersectionEnterTrigger";
  43127. case 12: return "OnIntersectionExitTrigger";
  43128. case 13: return "OnKeyDownTrigger";
  43129. case 14: return "OnKeyUpTrigger";
  43130. case 15: return "OnPickOutTrigger";
  43131. default: return "";
  43132. }
  43133. };
  43134. return ActionManager;
  43135. }());
  43136. // Statics
  43137. ActionManager._NothingTrigger = 0;
  43138. ActionManager._OnPickTrigger = 1;
  43139. ActionManager._OnLeftPickTrigger = 2;
  43140. ActionManager._OnRightPickTrigger = 3;
  43141. ActionManager._OnCenterPickTrigger = 4;
  43142. ActionManager._OnPickDownTrigger = 5;
  43143. ActionManager._OnDoublePickTrigger = 6;
  43144. ActionManager._OnPickUpTrigger = 7;
  43145. ActionManager._OnLongPressTrigger = 8;
  43146. ActionManager._OnPointerOverTrigger = 9;
  43147. ActionManager._OnPointerOutTrigger = 10;
  43148. ActionManager._OnEveryFrameTrigger = 11;
  43149. ActionManager._OnIntersectionEnterTrigger = 12;
  43150. ActionManager._OnIntersectionExitTrigger = 13;
  43151. ActionManager._OnKeyDownTrigger = 14;
  43152. ActionManager._OnKeyUpTrigger = 15;
  43153. ActionManager._OnPickOutTrigger = 16;
  43154. ActionManager.Triggers = {};
  43155. BABYLON.ActionManager = ActionManager;
  43156. })(BABYLON || (BABYLON = {}));
  43157. //# sourceMappingURL=babylon.actionManager.js.map
  43158. var BABYLON;
  43159. (function (BABYLON) {
  43160. var InterpolateValueAction = (function (_super) {
  43161. __extends(InterpolateValueAction, _super);
  43162. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43163. if (duration === void 0) { duration = 1000; }
  43164. var _this = _super.call(this, triggerOptions, condition) || this;
  43165. _this.propertyPath = propertyPath;
  43166. _this.value = value;
  43167. _this.duration = duration;
  43168. _this.stopOtherAnimations = stopOtherAnimations;
  43169. _this.onInterpolationDone = onInterpolationDone;
  43170. _this._target = _this._effectiveTarget = target;
  43171. return _this;
  43172. }
  43173. InterpolateValueAction.prototype._prepare = function () {
  43174. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43175. this._property = this._getProperty(this.propertyPath);
  43176. };
  43177. InterpolateValueAction.prototype.execute = function () {
  43178. var scene = this._actionManager.getScene();
  43179. var keys = [
  43180. {
  43181. frame: 0,
  43182. value: this._effectiveTarget[this._property]
  43183. }, {
  43184. frame: 100,
  43185. value: this.value
  43186. }
  43187. ];
  43188. var dataType;
  43189. if (typeof this.value === "number") {
  43190. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43191. }
  43192. else if (this.value instanceof BABYLON.Color3) {
  43193. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43194. }
  43195. else if (this.value instanceof BABYLON.Vector3) {
  43196. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43197. }
  43198. else if (this.value instanceof BABYLON.Matrix) {
  43199. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43200. }
  43201. else if (this.value instanceof BABYLON.Quaternion) {
  43202. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43203. }
  43204. else {
  43205. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43206. return;
  43207. }
  43208. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43209. animation.setKeys(keys);
  43210. if (this.stopOtherAnimations) {
  43211. scene.stopAnimation(this._effectiveTarget);
  43212. }
  43213. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  43214. };
  43215. InterpolateValueAction.prototype.serialize = function (parent) {
  43216. return _super.prototype._serialize.call(this, {
  43217. name: "InterpolateValueAction",
  43218. properties: [
  43219. BABYLON.Action._GetTargetProperty(this._target),
  43220. { name: "propertyPath", value: this.propertyPath },
  43221. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43222. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43223. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43224. ]
  43225. }, parent);
  43226. };
  43227. return InterpolateValueAction;
  43228. }(BABYLON.Action));
  43229. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43230. })(BABYLON || (BABYLON = {}));
  43231. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43232. var BABYLON;
  43233. (function (BABYLON) {
  43234. var SwitchBooleanAction = (function (_super) {
  43235. __extends(SwitchBooleanAction, _super);
  43236. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43237. var _this = _super.call(this, triggerOptions, condition) || this;
  43238. _this.propertyPath = propertyPath;
  43239. _this._target = _this._effectiveTarget = target;
  43240. return _this;
  43241. }
  43242. SwitchBooleanAction.prototype._prepare = function () {
  43243. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43244. this._property = this._getProperty(this.propertyPath);
  43245. };
  43246. SwitchBooleanAction.prototype.execute = function () {
  43247. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43248. };
  43249. SwitchBooleanAction.prototype.serialize = function (parent) {
  43250. return _super.prototype._serialize.call(this, {
  43251. name: "SwitchBooleanAction",
  43252. properties: [
  43253. BABYLON.Action._GetTargetProperty(this._target),
  43254. { name: "propertyPath", value: this.propertyPath }
  43255. ]
  43256. }, parent);
  43257. };
  43258. return SwitchBooleanAction;
  43259. }(BABYLON.Action));
  43260. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43261. var SetStateAction = (function (_super) {
  43262. __extends(SetStateAction, _super);
  43263. function SetStateAction(triggerOptions, target, value, condition) {
  43264. var _this = _super.call(this, triggerOptions, condition) || this;
  43265. _this.value = value;
  43266. _this._target = target;
  43267. return _this;
  43268. }
  43269. SetStateAction.prototype.execute = function () {
  43270. this._target.state = this.value;
  43271. };
  43272. SetStateAction.prototype.serialize = function (parent) {
  43273. return _super.prototype._serialize.call(this, {
  43274. name: "SetStateAction",
  43275. properties: [
  43276. BABYLON.Action._GetTargetProperty(this._target),
  43277. { name: "value", value: this.value }
  43278. ]
  43279. }, parent);
  43280. };
  43281. return SetStateAction;
  43282. }(BABYLON.Action));
  43283. BABYLON.SetStateAction = SetStateAction;
  43284. var SetValueAction = (function (_super) {
  43285. __extends(SetValueAction, _super);
  43286. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43287. var _this = _super.call(this, triggerOptions, condition) || this;
  43288. _this.propertyPath = propertyPath;
  43289. _this.value = value;
  43290. _this._target = _this._effectiveTarget = target;
  43291. return _this;
  43292. }
  43293. SetValueAction.prototype._prepare = function () {
  43294. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43295. this._property = this._getProperty(this.propertyPath);
  43296. };
  43297. SetValueAction.prototype.execute = function () {
  43298. this._effectiveTarget[this._property] = this.value;
  43299. if (this._target.markAsDirty) {
  43300. this._target.markAsDirty(this._property);
  43301. }
  43302. };
  43303. SetValueAction.prototype.serialize = function (parent) {
  43304. return _super.prototype._serialize.call(this, {
  43305. name: "SetValueAction",
  43306. properties: [
  43307. BABYLON.Action._GetTargetProperty(this._target),
  43308. { name: "propertyPath", value: this.propertyPath },
  43309. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43310. ]
  43311. }, parent);
  43312. };
  43313. return SetValueAction;
  43314. }(BABYLON.Action));
  43315. BABYLON.SetValueAction = SetValueAction;
  43316. var IncrementValueAction = (function (_super) {
  43317. __extends(IncrementValueAction, _super);
  43318. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43319. var _this = _super.call(this, triggerOptions, condition) || this;
  43320. _this.propertyPath = propertyPath;
  43321. _this.value = value;
  43322. _this._target = _this._effectiveTarget = target;
  43323. return _this;
  43324. }
  43325. IncrementValueAction.prototype._prepare = function () {
  43326. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43327. this._property = this._getProperty(this.propertyPath);
  43328. if (typeof this._effectiveTarget[this._property] !== "number") {
  43329. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43330. }
  43331. };
  43332. IncrementValueAction.prototype.execute = function () {
  43333. this._effectiveTarget[this._property] += this.value;
  43334. if (this._target.markAsDirty) {
  43335. this._target.markAsDirty(this._property);
  43336. }
  43337. };
  43338. IncrementValueAction.prototype.serialize = function (parent) {
  43339. return _super.prototype._serialize.call(this, {
  43340. name: "IncrementValueAction",
  43341. properties: [
  43342. BABYLON.Action._GetTargetProperty(this._target),
  43343. { name: "propertyPath", value: this.propertyPath },
  43344. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43345. ]
  43346. }, parent);
  43347. };
  43348. return IncrementValueAction;
  43349. }(BABYLON.Action));
  43350. BABYLON.IncrementValueAction = IncrementValueAction;
  43351. var PlayAnimationAction = (function (_super) {
  43352. __extends(PlayAnimationAction, _super);
  43353. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43354. var _this = _super.call(this, triggerOptions, condition) || this;
  43355. _this.from = from;
  43356. _this.to = to;
  43357. _this.loop = loop;
  43358. _this._target = target;
  43359. return _this;
  43360. }
  43361. PlayAnimationAction.prototype._prepare = function () {
  43362. };
  43363. PlayAnimationAction.prototype.execute = function () {
  43364. var scene = this._actionManager.getScene();
  43365. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43366. };
  43367. PlayAnimationAction.prototype.serialize = function (parent) {
  43368. return _super.prototype._serialize.call(this, {
  43369. name: "PlayAnimationAction",
  43370. properties: [
  43371. BABYLON.Action._GetTargetProperty(this._target),
  43372. { name: "from", value: String(this.from) },
  43373. { name: "to", value: String(this.to) },
  43374. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43375. ]
  43376. }, parent);
  43377. };
  43378. return PlayAnimationAction;
  43379. }(BABYLON.Action));
  43380. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43381. var StopAnimationAction = (function (_super) {
  43382. __extends(StopAnimationAction, _super);
  43383. function StopAnimationAction(triggerOptions, target, condition) {
  43384. var _this = _super.call(this, triggerOptions, condition) || this;
  43385. _this._target = target;
  43386. return _this;
  43387. }
  43388. StopAnimationAction.prototype._prepare = function () {
  43389. };
  43390. StopAnimationAction.prototype.execute = function () {
  43391. var scene = this._actionManager.getScene();
  43392. scene.stopAnimation(this._target);
  43393. };
  43394. StopAnimationAction.prototype.serialize = function (parent) {
  43395. return _super.prototype._serialize.call(this, {
  43396. name: "StopAnimationAction",
  43397. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43398. }, parent);
  43399. };
  43400. return StopAnimationAction;
  43401. }(BABYLON.Action));
  43402. BABYLON.StopAnimationAction = StopAnimationAction;
  43403. var DoNothingAction = (function (_super) {
  43404. __extends(DoNothingAction, _super);
  43405. function DoNothingAction(triggerOptions, condition) {
  43406. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43407. return _super.call(this, triggerOptions, condition) || this;
  43408. }
  43409. DoNothingAction.prototype.execute = function () {
  43410. };
  43411. DoNothingAction.prototype.serialize = function (parent) {
  43412. return _super.prototype._serialize.call(this, {
  43413. name: "DoNothingAction",
  43414. properties: []
  43415. }, parent);
  43416. };
  43417. return DoNothingAction;
  43418. }(BABYLON.Action));
  43419. BABYLON.DoNothingAction = DoNothingAction;
  43420. var CombineAction = (function (_super) {
  43421. __extends(CombineAction, _super);
  43422. function CombineAction(triggerOptions, children, condition) {
  43423. var _this = _super.call(this, triggerOptions, condition) || this;
  43424. _this.children = children;
  43425. return _this;
  43426. }
  43427. CombineAction.prototype._prepare = function () {
  43428. for (var index = 0; index < this.children.length; index++) {
  43429. this.children[index]._actionManager = this._actionManager;
  43430. this.children[index]._prepare();
  43431. }
  43432. };
  43433. CombineAction.prototype.execute = function (evt) {
  43434. for (var index = 0; index < this.children.length; index++) {
  43435. this.children[index].execute(evt);
  43436. }
  43437. };
  43438. CombineAction.prototype.serialize = function (parent) {
  43439. var serializationObject = _super.prototype._serialize.call(this, {
  43440. name: "CombineAction",
  43441. properties: [],
  43442. combine: []
  43443. }, parent);
  43444. for (var i = 0; i < this.children.length; i++) {
  43445. serializationObject.combine.push(this.children[i].serialize(null));
  43446. }
  43447. return serializationObject;
  43448. };
  43449. return CombineAction;
  43450. }(BABYLON.Action));
  43451. BABYLON.CombineAction = CombineAction;
  43452. var ExecuteCodeAction = (function (_super) {
  43453. __extends(ExecuteCodeAction, _super);
  43454. function ExecuteCodeAction(triggerOptions, func, condition) {
  43455. var _this = _super.call(this, triggerOptions, condition) || this;
  43456. _this.func = func;
  43457. return _this;
  43458. }
  43459. ExecuteCodeAction.prototype.execute = function (evt) {
  43460. this.func(evt);
  43461. };
  43462. return ExecuteCodeAction;
  43463. }(BABYLON.Action));
  43464. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43465. var SetParentAction = (function (_super) {
  43466. __extends(SetParentAction, _super);
  43467. function SetParentAction(triggerOptions, target, parent, condition) {
  43468. var _this = _super.call(this, triggerOptions, condition) || this;
  43469. _this._target = target;
  43470. _this._parent = parent;
  43471. return _this;
  43472. }
  43473. SetParentAction.prototype._prepare = function () {
  43474. };
  43475. SetParentAction.prototype.execute = function () {
  43476. if (this._target.parent === this._parent) {
  43477. return;
  43478. }
  43479. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43480. invertParentWorldMatrix.invert();
  43481. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43482. this._target.parent = this._parent;
  43483. };
  43484. SetParentAction.prototype.serialize = function (parent) {
  43485. return _super.prototype._serialize.call(this, {
  43486. name: "SetParentAction",
  43487. properties: [
  43488. BABYLON.Action._GetTargetProperty(this._target),
  43489. BABYLON.Action._GetTargetProperty(this._parent),
  43490. ]
  43491. }, parent);
  43492. };
  43493. return SetParentAction;
  43494. }(BABYLON.Action));
  43495. BABYLON.SetParentAction = SetParentAction;
  43496. var PlaySoundAction = (function (_super) {
  43497. __extends(PlaySoundAction, _super);
  43498. function PlaySoundAction(triggerOptions, sound, condition) {
  43499. var _this = _super.call(this, triggerOptions, condition) || this;
  43500. _this._sound = sound;
  43501. return _this;
  43502. }
  43503. PlaySoundAction.prototype._prepare = function () {
  43504. };
  43505. PlaySoundAction.prototype.execute = function () {
  43506. if (this._sound !== undefined)
  43507. this._sound.play();
  43508. };
  43509. PlaySoundAction.prototype.serialize = function (parent) {
  43510. return _super.prototype._serialize.call(this, {
  43511. name: "PlaySoundAction",
  43512. properties: [{ name: "sound", value: this._sound.name }]
  43513. }, parent);
  43514. };
  43515. return PlaySoundAction;
  43516. }(BABYLON.Action));
  43517. BABYLON.PlaySoundAction = PlaySoundAction;
  43518. var StopSoundAction = (function (_super) {
  43519. __extends(StopSoundAction, _super);
  43520. function StopSoundAction(triggerOptions, sound, condition) {
  43521. var _this = _super.call(this, triggerOptions, condition) || this;
  43522. _this._sound = sound;
  43523. return _this;
  43524. }
  43525. StopSoundAction.prototype._prepare = function () {
  43526. };
  43527. StopSoundAction.prototype.execute = function () {
  43528. if (this._sound !== undefined)
  43529. this._sound.stop();
  43530. };
  43531. StopSoundAction.prototype.serialize = function (parent) {
  43532. return _super.prototype._serialize.call(this, {
  43533. name: "StopSoundAction",
  43534. properties: [{ name: "sound", value: this._sound.name }]
  43535. }, parent);
  43536. };
  43537. return StopSoundAction;
  43538. }(BABYLON.Action));
  43539. BABYLON.StopSoundAction = StopSoundAction;
  43540. })(BABYLON || (BABYLON = {}));
  43541. //# sourceMappingURL=babylon.directActions.js.map
  43542. var BABYLON;
  43543. (function (BABYLON) {
  43544. var Debug;
  43545. (function (Debug) {
  43546. /**
  43547. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43548. */
  43549. var SkeletonViewer = (function () {
  43550. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43551. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43552. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43553. this.skeleton = skeleton;
  43554. this.mesh = mesh;
  43555. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43556. this.renderingGroupId = renderingGroupId;
  43557. this.color = BABYLON.Color3.White();
  43558. this._debugLines = [];
  43559. this._isEnabled = false;
  43560. this._scene = scene;
  43561. this.update();
  43562. this._renderFunction = this.update.bind(this);
  43563. }
  43564. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43565. get: function () {
  43566. return this._isEnabled;
  43567. },
  43568. set: function (value) {
  43569. if (this._isEnabled === value) {
  43570. return;
  43571. }
  43572. this._isEnabled = value;
  43573. if (value) {
  43574. this._scene.registerBeforeRender(this._renderFunction);
  43575. }
  43576. else {
  43577. this._scene.unregisterBeforeRender(this._renderFunction);
  43578. }
  43579. },
  43580. enumerable: true,
  43581. configurable: true
  43582. });
  43583. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43584. if (x === void 0) { x = 0; }
  43585. if (y === void 0) { y = 0; }
  43586. if (z === void 0) { z = 0; }
  43587. var tmat = BABYLON.Tmp.Matrix[0];
  43588. var parentBone = bone.getParent();
  43589. tmat.copyFrom(bone.getLocalMatrix());
  43590. if (x !== 0 || y !== 0 || z !== 0) {
  43591. var tmat2 = BABYLON.Tmp.Matrix[1];
  43592. BABYLON.Matrix.IdentityToRef(tmat2);
  43593. tmat2.m[12] = x;
  43594. tmat2.m[13] = y;
  43595. tmat2.m[14] = z;
  43596. tmat2.multiplyToRef(tmat, tmat);
  43597. }
  43598. if (parentBone) {
  43599. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  43600. }
  43601. tmat.multiplyToRef(meshMat, tmat);
  43602. position.x = tmat.m[12];
  43603. position.y = tmat.m[13];
  43604. position.z = tmat.m[14];
  43605. };
  43606. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  43607. var len = bones.length;
  43608. var meshPos = this.mesh.position;
  43609. for (var i = 0; i < len; i++) {
  43610. var bone = bones[i];
  43611. var points = this._debugLines[i];
  43612. if (!points) {
  43613. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43614. this._debugLines[i] = points;
  43615. }
  43616. this._getBonePosition(points[0], bone, meshMat);
  43617. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  43618. points[0].subtractInPlace(meshPos);
  43619. points[1].subtractInPlace(meshPos);
  43620. }
  43621. };
  43622. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  43623. var len = bones.length;
  43624. var boneNum = 0;
  43625. var meshPos = this.mesh.position;
  43626. for (var i = len - 1; i >= 0; i--) {
  43627. var childBone = bones[i];
  43628. var parentBone = childBone.getParent();
  43629. if (!parentBone) {
  43630. continue;
  43631. }
  43632. var points = this._debugLines[boneNum];
  43633. if (!points) {
  43634. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43635. this._debugLines[boneNum] = points;
  43636. }
  43637. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  43638. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  43639. points[0].subtractInPlace(meshPos);
  43640. points[1].subtractInPlace(meshPos);
  43641. boneNum++;
  43642. }
  43643. };
  43644. SkeletonViewer.prototype.update = function () {
  43645. if (this.autoUpdateBonesMatrices) {
  43646. this.skeleton.computeAbsoluteTransforms();
  43647. }
  43648. if (this.skeleton.bones[0].length === undefined) {
  43649. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43650. }
  43651. else {
  43652. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43653. }
  43654. if (!this._debugMesh) {
  43655. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  43656. this._debugMesh.renderingGroupId = this.renderingGroupId;
  43657. }
  43658. else {
  43659. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  43660. }
  43661. this._debugMesh.position.copyFrom(this.mesh.position);
  43662. this._debugMesh.color = this.color;
  43663. };
  43664. SkeletonViewer.prototype.dispose = function () {
  43665. if (this._debugMesh) {
  43666. this.isEnabled = false;
  43667. this._debugMesh.dispose();
  43668. this._debugMesh = null;
  43669. }
  43670. };
  43671. return SkeletonViewer;
  43672. }());
  43673. Debug.SkeletonViewer = SkeletonViewer;
  43674. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43675. })(BABYLON || (BABYLON = {}));
  43676. //# sourceMappingURL=babylon.skeletonViewer.js.map
  43677. var BABYLON;
  43678. (function (BABYLON) {
  43679. var Debug;
  43680. (function (Debug) {
  43681. var AxesViewer = (function () {
  43682. function AxesViewer(scene, scaleLines) {
  43683. if (scaleLines === void 0) { scaleLines = 1; }
  43684. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43685. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43686. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43687. this.scaleLines = 1;
  43688. this.scaleLines = scaleLines;
  43689. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  43690. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  43691. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  43692. this._xmesh.renderingGroupId = 2;
  43693. this._ymesh.renderingGroupId = 2;
  43694. this._zmesh.renderingGroupId = 2;
  43695. this._xmesh.material.checkReadyOnlyOnce = true;
  43696. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  43697. this._ymesh.material.checkReadyOnlyOnce = true;
  43698. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  43699. this._zmesh.material.checkReadyOnlyOnce = true;
  43700. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  43701. this.scene = scene;
  43702. }
  43703. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  43704. var scaleLines = this.scaleLines;
  43705. this._xmesh.position.copyFrom(position);
  43706. this._ymesh.position.copyFrom(position);
  43707. this._zmesh.position.copyFrom(position);
  43708. var point2 = this._xline[1];
  43709. point2.x = xaxis.x * scaleLines;
  43710. point2.y = xaxis.y * scaleLines;
  43711. point2.z = xaxis.z * scaleLines;
  43712. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  43713. point2 = this._yline[1];
  43714. point2.x = yaxis.x * scaleLines;
  43715. point2.y = yaxis.y * scaleLines;
  43716. point2.z = yaxis.z * scaleLines;
  43717. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  43718. point2 = this._zline[1];
  43719. point2.x = zaxis.x * scaleLines;
  43720. point2.y = zaxis.y * scaleLines;
  43721. point2.z = zaxis.z * scaleLines;
  43722. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  43723. };
  43724. AxesViewer.prototype.dispose = function () {
  43725. if (this._xmesh) {
  43726. this._xmesh.dispose();
  43727. this._ymesh.dispose();
  43728. this._zmesh.dispose();
  43729. this._xmesh = null;
  43730. this._ymesh = null;
  43731. this._zmesh = null;
  43732. this._xline = null;
  43733. this._yline = null;
  43734. this._zline = null;
  43735. this.scene = null;
  43736. }
  43737. };
  43738. return AxesViewer;
  43739. }());
  43740. Debug.AxesViewer = AxesViewer;
  43741. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43742. })(BABYLON || (BABYLON = {}));
  43743. //# sourceMappingURL=babylon.axesViewer.js.map
  43744. var BABYLON;
  43745. (function (BABYLON) {
  43746. var Debug;
  43747. (function (Debug) {
  43748. var BoneAxesViewer = (function (_super) {
  43749. __extends(BoneAxesViewer, _super);
  43750. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  43751. if (scaleLines === void 0) { scaleLines = 1; }
  43752. var _this = _super.call(this, scene, scaleLines) || this;
  43753. _this.pos = BABYLON.Vector3.Zero();
  43754. _this.xaxis = BABYLON.Vector3.Zero();
  43755. _this.yaxis = BABYLON.Vector3.Zero();
  43756. _this.zaxis = BABYLON.Vector3.Zero();
  43757. _this.mesh = mesh;
  43758. _this.bone = bone;
  43759. return _this;
  43760. }
  43761. BoneAxesViewer.prototype.update = function () {
  43762. var bone = this.bone;
  43763. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  43764. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  43765. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  43766. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  43767. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  43768. };
  43769. BoneAxesViewer.prototype.dispose = function () {
  43770. if (this.pos) {
  43771. this.pos = null;
  43772. this.xaxis = null;
  43773. this.yaxis = null;
  43774. this.zaxis = null;
  43775. this.mesh = null;
  43776. this.bone = null;
  43777. _super.prototype.dispose.call(this);
  43778. }
  43779. };
  43780. return BoneAxesViewer;
  43781. }(Debug.AxesViewer));
  43782. Debug.BoneAxesViewer = BoneAxesViewer;
  43783. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43784. })(BABYLON || (BABYLON = {}));
  43785. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  43786. var BABYLON;
  43787. (function (BABYLON) {
  43788. var RayHelper = (function () {
  43789. function RayHelper(ray) {
  43790. this.ray = ray;
  43791. }
  43792. RayHelper.CreateAndShow = function (ray, scene, color) {
  43793. var helper = new RayHelper(ray);
  43794. helper.show(scene, color);
  43795. return helper;
  43796. };
  43797. RayHelper.prototype.show = function (scene, color) {
  43798. if (!this._renderFunction) {
  43799. var ray = this.ray;
  43800. this._renderFunction = this._render.bind(this);
  43801. this._scene = scene;
  43802. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  43803. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  43804. this._scene.registerBeforeRender(this._renderFunction);
  43805. }
  43806. if (color) {
  43807. this._renderLine.color.copyFrom(color);
  43808. }
  43809. };
  43810. RayHelper.prototype.hide = function () {
  43811. if (this._renderFunction) {
  43812. this._scene.unregisterBeforeRender(this._renderFunction);
  43813. this._scene = null;
  43814. this._renderFunction = null;
  43815. this._renderLine.dispose();
  43816. this._renderLine = null;
  43817. this._renderPoints = null;
  43818. }
  43819. };
  43820. RayHelper.prototype._render = function () {
  43821. var ray = this.ray;
  43822. var point = this._renderPoints[1];
  43823. var len = Math.min(ray.length, 1000000);
  43824. point.copyFrom(ray.direction);
  43825. point.scaleInPlace(len);
  43826. point.addInPlace(ray.origin);
  43827. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  43828. };
  43829. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  43830. this._attachedToMesh = mesh;
  43831. var ray = this.ray;
  43832. if (!ray.direction) {
  43833. ray.direction = BABYLON.Vector3.Zero();
  43834. }
  43835. if (!ray.origin) {
  43836. ray.origin = BABYLON.Vector3.Zero();
  43837. }
  43838. if (length) {
  43839. ray.length = length;
  43840. }
  43841. if (!meshSpaceOrigin) {
  43842. meshSpaceOrigin = BABYLON.Vector3.Zero();
  43843. }
  43844. if (!meshSpaceDirection) {
  43845. // -1 so that this will work with Mesh.lookAt
  43846. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  43847. }
  43848. if (!this._meshSpaceDirection) {
  43849. this._meshSpaceDirection = meshSpaceDirection.clone();
  43850. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  43851. }
  43852. else {
  43853. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  43854. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  43855. }
  43856. if (!this._updateToMeshFunction) {
  43857. this._updateToMeshFunction = this._updateToMesh.bind(this);
  43858. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  43859. }
  43860. this._updateToMesh();
  43861. };
  43862. RayHelper.prototype.detachFromMesh = function () {
  43863. if (this._attachedToMesh) {
  43864. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  43865. this._attachedToMesh = null;
  43866. this._updateToMeshFunction = null;
  43867. }
  43868. };
  43869. RayHelper.prototype._updateToMesh = function () {
  43870. var ray = this.ray;
  43871. if (this._attachedToMesh._isDisposed) {
  43872. this.detachFromMesh();
  43873. return;
  43874. }
  43875. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  43876. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  43877. };
  43878. RayHelper.prototype.dispose = function () {
  43879. this.hide();
  43880. this.detachFromMesh();
  43881. this.ray = null;
  43882. };
  43883. return RayHelper;
  43884. }());
  43885. BABYLON.RayHelper = RayHelper;
  43886. })(BABYLON || (BABYLON = {}));
  43887. //# sourceMappingURL=babylon.rayHelper.js.map
  43888. var BABYLON;
  43889. (function (BABYLON) {
  43890. var DebugLayer = (function () {
  43891. function DebugLayer(scene) {
  43892. this._scene = scene;
  43893. }
  43894. /** Creates the inspector window. */
  43895. DebugLayer.prototype._createInspector = function (config) {
  43896. if (config === void 0) { config = {}; }
  43897. var popup = config.popup || false;
  43898. var initialTab = config.initialTab || 0;
  43899. var parentElement = config.parentElement || null;
  43900. if (!this._inspector) {
  43901. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  43902. } // else nothing to do,; instance is already existing
  43903. };
  43904. DebugLayer.prototype.isVisible = function () {
  43905. if (!this._inspector) {
  43906. return false;
  43907. }
  43908. return true;
  43909. };
  43910. DebugLayer.prototype.hide = function () {
  43911. if (this._inspector) {
  43912. try {
  43913. this._inspector.dispose();
  43914. }
  43915. catch (e) {
  43916. // If the inspector has been removed directly from the inspector tool
  43917. }
  43918. this._inspector = null;
  43919. }
  43920. };
  43921. DebugLayer.prototype.show = function (config) {
  43922. if (config === void 0) { config = {}; }
  43923. if (typeof INSPECTOR == 'undefined') {
  43924. // Load inspector and add it to the DOM
  43925. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  43926. }
  43927. else {
  43928. // Otherwise creates the inspector
  43929. this._createInspector(config);
  43930. }
  43931. };
  43932. return DebugLayer;
  43933. }());
  43934. // Get protocol used - http or https
  43935. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  43936. BABYLON.DebugLayer = DebugLayer;
  43937. })(BABYLON || (BABYLON = {}));
  43938. //# sourceMappingURL=babylon.debugLayer.js.map
  43939. var BABYLON;
  43940. (function (BABYLON) {
  43941. var BoundingBoxRenderer = (function () {
  43942. function BoundingBoxRenderer(scene) {
  43943. this.frontColor = new BABYLON.Color3(1, 1, 1);
  43944. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  43945. this.showBackLines = true;
  43946. this.renderList = new BABYLON.SmartArray(32);
  43947. this._vertexBuffers = {};
  43948. this._scene = scene;
  43949. }
  43950. BoundingBoxRenderer.prototype._prepareRessources = function () {
  43951. if (this._colorShader) {
  43952. return;
  43953. }
  43954. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  43955. attributes: [BABYLON.VertexBuffer.PositionKind],
  43956. uniforms: ["world", "viewProjection", "color"]
  43957. });
  43958. var engine = this._scene.getEngine();
  43959. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  43960. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  43961. 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]);
  43962. };
  43963. BoundingBoxRenderer.prototype.reset = function () {
  43964. this.renderList.reset();
  43965. };
  43966. BoundingBoxRenderer.prototype.render = function () {
  43967. if (this.renderList.length === 0) {
  43968. return;
  43969. }
  43970. this._prepareRessources();
  43971. if (!this._colorShader.isReady()) {
  43972. return;
  43973. }
  43974. var engine = this._scene.getEngine();
  43975. engine.setDepthWrite(false);
  43976. this._colorShader._preBind();
  43977. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  43978. var boundingBox = this.renderList.data[boundingBoxIndex];
  43979. var min = boundingBox.minimum;
  43980. var max = boundingBox.maximum;
  43981. var diff = max.subtract(min);
  43982. var median = min.add(diff.scale(0.5));
  43983. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  43984. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  43985. .multiply(boundingBox.getWorldMatrix());
  43986. // VBOs
  43987. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  43988. if (this.showBackLines) {
  43989. // Back
  43990. engine.setDepthFunctionToGreaterOrEqual();
  43991. this._scene.resetCachedMaterial();
  43992. this._colorShader.setColor4("color", this.backColor.toColor4());
  43993. this._colorShader.bind(worldMatrix);
  43994. // Draw order
  43995. engine.draw(false, 0, 24);
  43996. }
  43997. // Front
  43998. engine.setDepthFunctionToLess();
  43999. this._scene.resetCachedMaterial();
  44000. this._colorShader.setColor4("color", this.frontColor.toColor4());
  44001. this._colorShader.bind(worldMatrix);
  44002. // Draw order
  44003. engine.draw(false, 0, 24);
  44004. }
  44005. this._colorShader.unbind();
  44006. engine.setDepthFunctionToLessOrEqual();
  44007. engine.setDepthWrite(true);
  44008. };
  44009. BoundingBoxRenderer.prototype.dispose = function () {
  44010. if (!this._colorShader) {
  44011. return;
  44012. }
  44013. this.renderList.dispose();
  44014. this._colorShader.dispose();
  44015. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44016. if (buffer) {
  44017. buffer.dispose();
  44018. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44019. }
  44020. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44021. };
  44022. return BoundingBoxRenderer;
  44023. }());
  44024. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  44025. })(BABYLON || (BABYLON = {}));
  44026. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  44027. var BABYLON;
  44028. (function (BABYLON) {
  44029. var TextureTools = (function () {
  44030. function TextureTools() {
  44031. }
  44032. /**
  44033. * Uses the GPU to create a copy texture rescaled at a given size
  44034. * @param texture Texture to copy from
  44035. * @param width Desired width
  44036. * @param height Desired height
  44037. * @return Generated texture
  44038. */
  44039. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  44040. if (useBilinearMode === void 0) { useBilinearMode = true; }
  44041. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  44042. var scene = texture.getScene();
  44043. var engine = scene.getEngine();
  44044. rtt.wrapU = texture.wrapU;
  44045. rtt.wrapV = texture.wrapV;
  44046. rtt.uOffset = texture.uOffset;
  44047. rtt.vOffset = texture.vOffset;
  44048. rtt.uScale = texture.uScale;
  44049. rtt.vScale = texture.vScale;
  44050. rtt.uAng = texture.uAng;
  44051. rtt.vAng = texture.vAng;
  44052. rtt.wAng = texture.wAng;
  44053. rtt.coordinatesIndex = texture.coordinatesIndex;
  44054. rtt.level = texture.level;
  44055. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  44056. rtt._texture.isReady = false;
  44057. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44058. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44059. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  44060. passPostProcess.getEffect().executeWhenCompiled(function () {
  44061. passPostProcess.onApply = function (effect) {
  44062. effect.setTexture("textureSampler", texture);
  44063. };
  44064. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  44065. engine.unBindFramebuffer(rtt.getInternalTexture());
  44066. rtt.disposeFramebufferObjects();
  44067. passPostProcess.dispose();
  44068. rtt._texture.isReady = true;
  44069. });
  44070. return rtt;
  44071. };
  44072. return TextureTools;
  44073. }());
  44074. BABYLON.TextureTools = TextureTools;
  44075. })(BABYLON || (BABYLON = {}));
  44076. //# sourceMappingURL=babylon.textureTools.js.map
  44077. BABYLON.Effect.ShadersStore={"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;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\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>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\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 float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\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}","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<__decl__lightFragment>[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}","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}","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]\n#ifdef PACKEDFLOAT\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}\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\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\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}","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}","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}","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<__decl__lightFragment>[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}"};
  44078. 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","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","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(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","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};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec3 shadowsInfo{X};\nuniform vec2 depthValues{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","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;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\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};","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;","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","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\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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 computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample)))-darkness,0.,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\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))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\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}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample)))-darkness,0.,1.);\n\n\n\n\n\nreturn esm;\n}\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,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","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}","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}","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}","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}","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 SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else\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,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{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,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{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,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\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","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\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","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};"};
  44079. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  44080. module.exports = BABYLON;
  44081. };